﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using DAL.Entity;
using DAL.Persistencia;
using System.Globalization;
using NewTierra.App_Code;

namespace NewTierra.Externo4Star
{
    public partial class QuoteGeralNew : System.Web.UI.Page
    {
        public static string FlagFirst;
        public static int NumRange;
        public static string DivDescr;
        public static string TdQuote;
        public static string MoedaQuote;
        public static string UrlEmpresa;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FlagFirst = "S";
                NumRange = 1;
                DivDescr = "none";
                TdQuote = "block";

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();

                UrlEmpresa = ConfigurationManager.AppSettings["UrlEmpresa"].ToString();
                //ddlTipoQuote.SelectedValue = Request.QueryString["type"];

                if (Request.QueryString["Code"].Equals(""))
                {
                    int IdQuote = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;
                    lblNumQuote.Text = Session["Quotation_Code"].ToString();
                    VerificaExtra();

                    //if (ConfigurationManager.AppSettings["PuxaLogo"].ToString().Equals("4Star"))
                    //{
                    //    int BaseDe = Convert.ToInt32(ftd.ListarTodosRangeZero(IdQuote).First().Paying_Pax);

                    //    //txtRangeDe.Text = BaseDe.ToString();
                    //    //txtRangePara.Text = BaseDe.ToString();
                    //    PanelAddRanges.Visible = true;

                    //    MontaEntrada();
                    //}
                    //else
                    //{
                    MontaSeguintesNewFile();
                    //}
                }
                else
                {
                    PreencheLink(Request.QueryString["Code"]);
                }

                switch (ConfigurationManager.AppSettings["PuxaLogo"].ToString())
                {
                    case "4Star":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/logo4star.png";
                        break;
                    case "Compass":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/LogoCompass2.png";
                        break;
                    case "DelBianco":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/logoDelBianco.jpg";
                        imgLogo.CssClass = "LogoDelBianco";
                        break;
                    case "Rentamar":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/logoRentamar.png";
                        imgLogo.CssClass = "LogoRentamar";
                        break;
                    case "ElcoTour":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/logoElcotour.png";
                        break;
                    case "NorthSide":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/LogoNorthSide.jpg";
                        break;
                    case "Panoramabrazil":
                        imgLogo.ImageUrl = UrlEmpresa + "/images/Logo-Panorama.png";
                        break;
                }

                if (Request.QueryString["Code"].ToString() == "")
                {
                    CarregaHotels();
                    CarregaHighlights();
                }
                else
                {
                    CarregaHotelsPorCodigo();
                    CarregaHighlightsPorCodigo();
                }

                CarregaTourMap();
            }
        }

        #region Popula Dados

        protected void CarregaHotels()
        {
            try
            {
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                int IdQuote = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;

                DataTable dt = new DataTable();
                dt.Columns.Add("imgStars");
                dt.Columns.Add("idSupplier");
                dt.Columns.Add("nomeHotel");
                dt.Columns.Add("cidade");
                dt.Columns.Add("descricaoHotel");
                dt.Columns.Add("imgHotel");

                int lastSupplierID = 0;

                foreach (File_Tarifas ft in new FileTarifasDAL().ListarTodosRangeZero(IdQuote))
                {
                    S_Categoria Categoria = new CategoriaDAL().ObterPorSupp(Convert.ToInt32(ft.S_id));
                    Supplier s = new SupplierDAL().ObterPorId(Convert.ToInt32(ft.S_id));

                    if (lastSupplierID == s.S_id)
                        continue;

                    lastSupplierID = s.S_id;


                    string imgStars = "";

                    if (Categoria != null)
                    {
                        imgStars = UrlEmpresa + "/imgCategorias/" + Categoria.Categ_imgnome;
                    }
                    else
                    {
                        imgStars = UrlEmpresa + "/imgCategorias/semcategoria.gif";
                    }

                    Cidade Cidade = new CidadeDAL().ObterPorNomeSupplier(s.S_nome);
                    Pai pais = new PaisDAL().ObterPorId(Convert.ToInt32(s.PAIS_id));
                    string fotoReziseTemp = "", fotoResize = "";

                    if (Request.QueryString["foto"].Equals("0"))
                    {
                        FotoDAL fd = new FotoDAL();
                        S_Image si = fd.ObterPorSupplierCapa(s.S_id);
                        ResizeFoto rf = new ResizeFoto();

                        if (si != null)
                        {
                            fotoReziseTemp = "/temp/" + si.Image_nome;
                            fotoResize = "/Galeria/" + s.S_id + "/" + si.Image_nome;
                            rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);
                        }
                        else
                        {
                            fotoReziseTemp = "/temp/semimagem.jpg";
                            fotoResize = "/Galeria/semimagem.jpg";
                            rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);
                        }

                        rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);
                    }

                    S_Descricao descricao = new DescricaoDAL().ObterPorIdSupp(Convert.ToInt32(ft.S_id));

                    string descr = "";
                    if (descricao != null) descr = descricao.Desc_long; else descr = "No description";

                    if (Request.QueryString["foto"] == "0")
                        dt.Rows.Add(imgStars, ft.S_id, ft.S_nome, Cidade.CID_nome + " - " + pais.PAIS_nome, descr, UrlEmpresa + fotoReziseTemp);
                    else
                        dt.Rows.Add(imgStars, ft.S_id, ft.S_nome, Cidade.CID_nome + " - " + pais.PAIS_nome, descr, "");

                }

                rptHotel.DataSource = dt;
                rptHotel.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void CarregaHotelsPorCodigo()
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("imgStars");
                dt.Columns.Add("idSupplier");
                dt.Columns.Add("nomeHotel");
                dt.Columns.Add("cidade");
                dt.Columns.Add("descricaoHotel");
                dt.Columns.Add("imgHotel");

                int lastSupplierID = 0;

                foreach (var ft in new TBItineraryDAL().ListarTodosHOTEL(Request.QueryString["Code"]))
                {
                    S_Categoria Categoria = new CategoriaDAL().ObterPorSupp(Convert.ToInt32(ft.S_id));
                    Supplier s = new SupplierDAL().ObterPorId(Convert.ToInt32(ft.S_id));

                    if (lastSupplierID == s.S_id)
                        continue;

                    lastSupplierID = s.S_id;

                    string imgStars = "";

                    if (Categoria != null)
                    {
                        imgStars = UrlEmpresa + "/imgCategorias/" + Categoria.Categ_imgnome;
                    }
                    else
                    {
                        imgStars = UrlEmpresa + "/imgCategorias/semcategoria.gif";
                    }

                    Cidade Cidade = new CidadeDAL().ObterPorNomeSupplier(s.S_nome);
                    Pai pais = new PaisDAL().ObterPorId(Convert.ToInt32(s.PAIS_id));

                    string fotoReziseTemp = "";

                    if (Request.QueryString["foto"].Equals("0"))
                    {
                        FotoDAL fd = new FotoDAL();
                        S_Image si = fd.ObterPorSupplierCapa(s.S_id);
                        if (si != null)
                        {
                            fotoReziseTemp = "/temp/" + si.Image_nome;
                            string fotoResize = "/Galeria/" + s.S_id + "/" + si.Image_nome;
                            ResizeFoto rf = new ResizeFoto();
                            rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);
                        }
                        else
                        {
                            fotoReziseTemp = "/temp/semimagem.jpg";
                            string fotoResize = "/Galeria/semimagem.jpg";
                            ResizeFoto rf = new ResizeFoto();
                            rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);
                        }
                    }

                    S_Descricao descricao = new DescricaoDAL().ObterPorIdSupp(Convert.ToInt32(ft.S_id));

                    string descr = "";
                    if (descricao != null) descr = descricao.Desc_long; else descr = "No description";

                    if (Request.QueryString["foto"] == "0")
                        dt.Rows.Add(imgStars, ft.S_id, ft.SuppNome, Cidade.CID_nome + " - " + pais.PAIS_nome, descr, UrlEmpresa + fotoReziseTemp);
                    else
                        dt.Rows.Add(imgStars, ft.S_id, ft.SuppNome, Cidade.CID_nome + " - " + pais.PAIS_nome, descr, "");
                }

                rptHotel.DataSource = dt;
                rptHotel.DataBind();

                TBItinerary tbi = new TBItineraryDAL().ListarTodosCode(Request.QueryString["Code"].ToString()).FirstOrDefault();
                lblNumQuote.Text = tbi.Quotation_Code;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void CarregaHighlights()
        {
            FileCarrinhoDAL fcd = new FileCarrinhoDAL();
            int IdQuote = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;

            hdfFileID.Value = IdQuote.ToString();

            DataTable dt = new DataTable();
            dt.Columns.Add("cityName");
            dt.Columns.Add("cityID");

            Dictionary<int, string> cidade = new Dictionary<int, string>();

            var lstft = new FileTransfersDAL().ListarTodosRangeZero(IdQuote);

            DateTime dtIn = Convert.ToDateTime(lstft.OrderBy(a => a.Data_From).ToList()[0].Data_From);
            DateTime dtOut = Convert.ToDateTime(lstft.OrderByDescending(a => a.Data_To).ToList()[0].Data_To);

            int dias = Convert.ToInt32(dtOut.Subtract(dtIn).TotalDays);
            lblNumDias.Text = dias.ToString() + " days / " + (dias - 1).ToString() + " nights";

            foreach (File_Transfers ft in lstft)
            {
                var city = new CidadeDAL().ObterPorId((int)ft.Trf_CID_id);

                if (city != null)
                {
                    bool alreadyInCidades = false;
                    foreach (KeyValuePair<int, string> kvp in cidade)
                    {
                        if (kvp.Key == city.CID_id)
                            alreadyInCidades = true;
                    }

                    if (!alreadyInCidades)
                        cidade.Add(city.CID_id, city.CID_nome);
                }
            }


            var listaCidades = cidade.OrderBy(a => a.Value);

            string last = "";

            foreach (KeyValuePair<int, string> cid in listaCidades)
            {
                if (cid.Value != last)
                    dt.Rows.Add(cid.Value, cid.Key);

                last = cid.Value;
            }

            rptCities.DataSource = dt;
            rptCities.DataBind();

            if (Request.QueryString["foto"] == "0")
            {
                S_Servicos firstServ = new ServicoDAL().ObterPorNome(lstft.First().Transf_nome);
                Servicos_Imagem siFirst = new FotoServicoDAL().ObterImgPrincipal(firstServ.Servicos_Id);

                if (siFirst != null)
                    imgHighlight1.ImageUrl = "~/Galeria/Servicos/" + firstServ.Servicos_Id + "/" + siFirst.Serv_img_nome;

                S_Servicos lastServ = new ServicoDAL().ObterPorNome(lstft.Last().Transf_nome);
                Servicos_Imagem siLast = new FotoServicoDAL().ObterImgPrincipal(lastServ.Servicos_Id);

                if (siLast != null)
                    imgHighlight2.ImageUrl = "~/Galeria/Servicos/" + lastServ.Servicos_Id + "/" + siLast.Serv_img_nome;
            }
        }

        private void CarregaHighlightsPorCodigo()
        {

            try
            {

                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                List<TBItinerary> lstIt = new TBItineraryDAL().ListarTodosCode(Request.QueryString["Code"].ToString());

                if (lstIt.Count <= 0)
                    return;

                Quotation q = new QuotationDAL().ObterPorCode(lstIt[0].Quotation_Code);
                Quotation_Grupo qg = new QuotationGrupoDAL().ObterPorIdQuotation(q.Quotation_Id);

                int IdQuote = fcd.ObterPorIdGrupo(qg.Quotation_Grupo_Id).File_id;

                hdfFileID.Value = IdQuote.ToString();

                DataTable dt = new DataTable();
                dt.Columns.Add("cityName");
                dt.Columns.Add("cityID");

                Dictionary<int, string> cidade = new Dictionary<int, string>();

                var lstft = new FileTransfersDAL().ListarTodosRangeZero(IdQuote);

                DateTime dtIn = Convert.ToDateTime(lstft.OrderBy(a => a.Data_From).ToList()[0].Data_From);
                DateTime dtOut = Convert.ToDateTime(lstft.OrderByDescending(a => a.Data_To).ToList()[0].Data_To);

                int dias = Convert.ToInt32(dtOut.Subtract(dtIn).TotalDays);
                lblNumDias.Text = dias.ToString() + " days / " + (dias - 1).ToString() + " nights";

                foreach (File_Transfers ft in lstft)
                {
                    var city = new CidadeDAL().ObterPorId((int)ft.Trf_CID_id);

                    if (city != null)
                    {
                        bool alreadyInCidades = false;
                        foreach (KeyValuePair<int, string> kvp in cidade)
                        {
                            if (kvp.Key == city.CID_id)
                                alreadyInCidades = true;
                        }

                        if (!alreadyInCidades)
                            cidade.Add(city.CID_id, city.CID_nome);
                    }
                }


                var listaCidades = cidade.OrderBy(a => a.Value);

                string last = "";

                foreach (KeyValuePair<int, string> cid in listaCidades)
                {
                    if (cid.Value != last)
                        dt.Rows.Add(cid.Value, cid.Key);

                    last = cid.Value;
                }

                rptCities.DataSource = dt;
                rptCities.DataBind();


                if (Request.QueryString["foto"] == "0")
                {
                    S_Servicos firstServ = new ServicoDAL().ObterPorNome(lstft.First().Transf_nome);
                    Servicos_Imagem siFirst = new FotoServicoDAL().ObterImgPrincipal(firstServ.Servicos_Id);

                    if (siFirst != null)
                        imgHighlight1.ImageUrl = "~/Galeria/Servicos/" + firstServ.Servicos_Id + "/" + siFirst.Serv_img_nome;

                    S_Servicos lastServ = new ServicoDAL().ObterPorNome(lstft.Last().Transf_nome);
                    Servicos_Imagem siLast = new FotoServicoDAL().ObterImgPrincipal(lastServ.Servicos_Id);

                    if (siLast != null)
                        imgHighlight2.ImageUrl = "~/Galeria/Servicos/" + lastServ.Servicos_Id + "/" + siLast.Serv_img_nome;
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion

        protected void VerificaExtra()
        {
            try
            {

                FileServExtraDAL fsed = new FileServExtraDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();

                int IdQuote = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;

                List<File_ServExtra> fs = fsed.ListarTodos(IdQuote);

                if (fs.Count() != 0)
                {

                    ViewState["VerificaExtra"] = "S";

                    DataTable dummy = new DataTable();
                    dummy.Columns.Add("NomeExtra");
                    dummy.Columns.Add("IdExtra");

                    foreach (File_ServExtra item in fs)
                    {
                        DataRow drw = dummy.NewRow();

                        drw["NomeExtra"] = item.S_nome;
                        drw["IdExtra"] = item.File_ServExtra_id;

                        dummy.Rows.Add(drw);
                    }

                    dlValoresServExtra.DataSource = dummy;
                    dlValoresServExtra.DataBind();

                    int num = Convert.ToInt32(fs.First().Paying_Pax);

                    //if ((Convert.ToInt32(txtRangeDe.Text.Trim()) != fs.First().Paying_Pax))
                    //{
                    //    ModalPopupValueExtra.Show();
                    //}
                }
                else
                {
                    ViewState["VerificaExtra"] = "N";
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void PreencheLink(string Code)
        {
            try
            {
                TdQuote = "none";

                TBItineraryDAL tbid = new TBItineraryDAL();

                dlNomesQuote.DataSource = tbid.ListarTodosCode(Code);
                dlNomesQuote.DataBind();

                PanelAddRanges.Visible = false;
                lnkGerarLink.Visible = false;
                //btnOrdenar.Visible = true;

                GeraTotais(Code);

                dlQuote.DataSource = tbid.ListarTodosCode(Code);
                dlQuote.DataBind();

                ChangeDlQuote();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void MontaEntrada()
        {
            try
            {
                CidadeDAL cd = new CidadeDAL();
                SupplierDAL spd = new SupplierDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL fts = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                TBItineraryDAL tbid = new TBItineraryDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                TarifaDAL tard = new TarifaDAL();
                MontaServicoDAL msd = new MontaServicoDAL();
                MoedaDAL mod = new MoedaDAL();
                CambioDAL cambDal = new CambioDAL();
                SBaseValorDAL sbaseV = new SBaseValorDAL();
                ServicoDAL servDal = new ServicoDAL();
                //TipoRoomDAL troomdal = new TipoRoomDAL();

                string Code = GerarCode();

                ViewState["Code"] = Code;

                int IdQuote = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;

                File_Tarifas ftsing = ftd.ListarTodosRangeZero(IdQuote).First();

                //ddlRooms.SelectedValue = ftsing.Room_id.ToString(); //ftd.ListarTodos(IdQuote).First().Room_id.ToString();

                DataTable dummy = new DataTable();
                dummy.Columns.Add("Room");
                dummy.Columns.Add("Base");
                dummy.Columns.Add("Price");

                decimal soma = 0;


                Moeda moedaQ = mod.ObterPorId(Convert.ToInt32(Session["IdMoedaQuote"]));
                MoedaQuote = moedaQ.Moeda_sigla;

                DataRow drw = dummy.NewRow();
                //drw["Base"] = txtRangeDe.Text + " to " + txtRangePara.Text + ")";
                //drw["Room"] = "Total per person in " + ddlRooms.SelectedItem + " (Travelers from ";

                foreach (File_Tarifas ft in ftd.ListarTodosRangeZero(IdQuote))
                {
                    TBItinerary tbi = new TBItinerary();

                    Quotation_TourMap qtm = new Quotation_TourMapDAL().ObterPorQuotationGrupoID(Convert.ToInt32(Session["SSIdQuotGrupo"]));

                    if (qtm != null)
                    {
                        tbi.tourmap = qtm.tourMap_Path;
                    }

                    tbi.Code = Code;
                    tbi.DateFrom = ft.Data_From;
                    tbi.DateTo = ft.Data_To;
                    tbi.SuppNome = ft.S_nome;

                    if (Convert.ToBoolean(ft.Meal))
                    {
                        tbi.Flag = "MEAL";

                        if (ft.S_meal_status != null)
                        {
                            tbi.MealNome = ft.S_meal_nome + " " + ft.S_meal_status;
                        }
                        else
                        {
                            tbi.MealNome = ft.S_meal_nome;
                        }
                    }
                    else
                    {
                        tbi.Room = ft.Room;
                        tbi.Categoria = ft.Categoria;

                        tbi.Flag = "HOTEL";
                        tbi.NomePacote = ft.NomePacote;
                    }

                    tbi.S_id = ft.S_id;
                    tbi.idTabela = ft.File_Tarifas_id;
                    tbi.Quotation_Code = Session["Quotation_Code"].ToString();
                    tbi.Ordem = ft.Ordem;

                    Supplier sp = spd.ObterPorId(Convert.ToInt32(ft.S_id));

                    tbi.Cidade = sp.Cidade.CID_nome;

                    if (ft.Flights_id != null)
                    {
                        FileFlightsDAL ffd = new FileFlightsDAL();

                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ft.Flights_id));

                        tbi.Flight_voo = ff.Flights_nome;
                        tbi.Flight_hora = ff.Flights_hora;
                        tbi.Flight_pickUp = ff.Flights_pickUp;
                    }


                    if (ft.Meal == null)
                    {

                        //--------------------------------------CALCULAR VALORES TARIFAS

                        //if (ft.Room_id != Convert.ToInt32(ddlRooms.SelectedValue))
                        //{

                        //    //S_Mercado_Tarifa smtarifa = tard.ListarTodosHoteisTarifasLista(Convert.ToDateTime(ft.Data_From),
                        //    //                                                               Convert.ToDateTime(ft.Data_To),
                        //    //                                                               Convert.ToInt32(ft.S_id),
                        //    //                                                               Convert.ToInt32(ddlRooms.SelectedValue),
                        //    //                                                               Convert.ToInt32(ft.Categoria_id));

                        //    S_Mercado_Tarifa smtarifa = tard.ListarTodosHoteisTarifasLista(Convert.ToDateTime(ft.Data_From),
                        //                                                                   Convert.ToDateTime(ft.Data_To),
                        //                                                                   Convert.ToInt32(ft.S_id),
                        //                                                                   Convert.ToInt32(ft.Room_id),
                        //                                                                   Convert.ToInt32(ft.Categoria_id));

                        //    if (smtarifa.S_Mercado_Periodo.Moeda_id != Convert.ToInt32(Session["IdMoedaQuote"]))
                        //    {
                        //        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(smtarifa.S_Mercado_Periodo.Moeda_id), Convert.ToInt32(Session["IdMoedaQuote"]));

                        //        decimal valor = Convert.ToDecimal(ft.S_merc_tarif_venda);

                        //        decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        //        decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                        //        decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                        //        decimal addMark = ((valorComCambio * MarkupCliente) / 100) + valorComCambio;

                        //        decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                        //        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        //        {
                        //            MarkupPaisDAL mkd = new MarkupPaisDAL();

                        //            Supplier spp = spd.ObterPorId(Convert.ToInt32(ft.S_id));
                        //            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        //            decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.Markup)) / 100) + addDesc;
                        //            decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                tbi.Range01 = addDescNet / smtarifa.Tipo_Room.Tipo_room_number;
                        //            }
                        //            else
                        //            {
                        //                tbi.Range01 = addDescNet;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                tbi.Range01 = addDesc / smtarifa.Tipo_Room.Tipo_room_number;
                        //            }
                        //            else
                        //            {
                        //                tbi.Range01 = addDesc;
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                        //        decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                        //        decimal addMark = ((Convert.ToDecimal(smtarifa.S_merc_tarif_tarifa_total) * MarkupCliente) / 100) + Convert.ToDecimal(smtarifa.S_merc_tarif_tarifa_total);

                        //        decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                        //        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        //        {
                        //            MarkupPaisDAL mkd = new MarkupPaisDAL();

                        //            Supplier spp = spd.ObterPorId(Convert.ToInt32(ft.S_id));
                        //            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        //            decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.Markup)) / 100) + addDesc;
                        //            decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                tbi.Range01 = addDesc / smtarifa.Tipo_Room.Tipo_room_number;
                        //            }
                        //            else
                        //            {
                        //                tbi.Range01 = addDescNet;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                tbi.Range01 = addDesc / smtarifa.Tipo_Room.Tipo_room_number;
                        //            }
                        //            else
                        //            {
                        //                tbi.Range01 = addDesc;
                        //            }
                        //        }
                        //    }

                        //}
                        //else
                        //{
                        tbi.Range01 = ft.S_merc_tarif_venda;
                        //tbi.Range01 = ft.S_merc_tarif_total;
                        //}

                        soma = soma + Convert.ToDecimal(tbi.Range01);

                    }
                    else if (ft.Meal != null && ft.S_meal_status == null)
                    {
                        //--------------------------------------CALCULAR VALORES MEAL

                        //tbi.Range01 = ft.S_merc_tarif_total;
                        tbi.Range01 = ft.S_merc_tarif_venda;

                        soma = soma + Convert.ToDecimal(tbi.Range01);

                    }
                    else
                    {
                        tbi.Range01 = 0;
                        soma = soma + 0;
                    }

                    //tbi.Base01 = txtRangeDe.Text + "/" + txtRangePara.Text;

                    tbid.Salvar(tbi);


                }

                foreach (File_Transfers ft in fts.ListarTodosRangeZero(IdQuote))
                {
                    TBItinerary tbi = new TBItinerary();

                    Quotation_TourMap qtm = new Quotation_TourMapDAL().ObterPorQuotationGrupoID(Convert.ToInt32(Session["SSIdQuotGrupo"]));

                    if (qtm != null)
                    {
                        tbi.tourmap = qtm.tourMap_Path;
                    }

                    tbi.Code = Code;
                    tbi.ServNome = ft.Transf_nome;
                    tbi.DateFrom = ft.Data_From;
                    tbi.DateTo = ft.Data_To;
                    tbi.S_id = ft.S_id;
                    tbi.idTabela = ft.File_Transf_id;
                    tbi.Quotation_Code = Session["Quotation_Code"].ToString();
                    tbi.Ordem = ft.Ordem;

                    if (ft.Flights_id != null)
                    {
                        FileFlightsDAL ffd = new FileFlightsDAL();

                        File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ft.Flights_id));

                        tbi.Flight_voo = ff.Flights_nome;
                        tbi.Flight_hora = ff.Flights_hora;
                        tbi.Flight_pickUp = ff.Flights_pickUp;
                    }

                    int IdMoeda = 0;
                    decimal tarifa = 0;


                    //if (Convert.ToInt32(txtRangeDe.Text.Trim()) == ft.Paying_Pax)
                    //{

                    //    tarifa = Convert.ToDecimal(ft.Transf_venda);
                    //    //tarifa = Convert.ToDecimal(ft.Transf_total);
                    //    tbi.Range01 = tarifa;
                    //}
                    //else
                    //{

                    //if (ft.SubServico != null)
                    //{
                    //    S_Bases_Valor sbv = sbaseV.ObterValorSub(Convert.ToInt32(ft.S_id),
                    //                                             ft.Transf_nome,
                    //                                             Convert.ToDateTime(ft.Data_From),
                    //                                             Convert.ToDateTime(ft.Data_To),
                    //                                             Convert.ToInt32(txtRangeDe.Text));
                    //    IdMoeda = sbv.S_Bases.Moeda_id;
                    //    tarifa = Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                    //}
                    //else
                    //{
                    //    Monta_Servico_Valores msvv;

                    //    if (ft.Trf_CID_id != null)
                    //    {

                    //        msvv = msd.ObterValorTransfers(Convert.ToDateTime(ft.Data_From),
                    //                                                            Convert.ToDateTime(ft.Data_To),
                    //                                                            Convert.ToInt32(ft.S_id),
                    //                                                            Convert.ToInt32(txtRangeDe.Text),
                    //                                                            ft.Transf_nome,
                    //                                                            Convert.ToInt32(ft.Trf_CID_id));
                    //    }
                    //    else
                    //    {
                    //        msvv = msd.ObterValorTransfers(Convert.ToDateTime(ft.Data_From),
                    //                                                             Convert.ToDateTime(ft.Data_To),
                    //                                                             Convert.ToInt32(ft.S_id),
                    //                                                             Convert.ToInt32(txtRangeDe.Text),
                    //                                                             ft.Transf_nome);
                    //    }

                    //    IdMoeda = msvv.S_Bases.Moeda_id;
                    //    tarifa = Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                    //}

                    //if (IdMoeda != Convert.ToInt32(Session["IdMoedaQuote"]))
                    //{
                    //    Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(Session["IdMoedaQuote"]));

                    //    decimal valor = Convert.ToDecimal(tarifa);

                    //    decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                    //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    //    decimal addMark = ((valorComCambio * MarkupCliente) / 100) + valorComCambio;

                    //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                    //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    //    {
                    //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                    //        Supplier spp = spd.ObterPorId(Convert.ToInt32(ft.S_id));
                    //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                    //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                    //        decimal v = Convert.ToInt32(ft.Paying_Pax) * addDescNet;

                    //        //tbi.Range01 = addDescNet;
                    //        tbi.Range01 = v;
                    //    }
                    //    else
                    //    {
                    //        decimal v = Convert.ToInt32(ft.Paying_Pax) * addDesc;

                    //        //tbi.Range01 = addDesc;
                    //        tbi.Range01 = v;
                    //    }
                    //}
                    //else
                    //{
                    //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    //    decimal addMark = ((Convert.ToDecimal(tarifa) * MarkupCliente) / 100) + Convert.ToDecimal(tarifa);

                    //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                    //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    //    {
                    //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                    //        Supplier spp = spd.ObterPorId(Convert.ToInt32(ft.S_id));
                    //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                    //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                    //        tbi.Range01 = addDescNet;
                    //    }
                    //    else
                    //    {
                    //        tbi.Range01 = addDesc;
                    //    }
                    //}

                    //}


                    //tbi.Base01 = txtRangeDe.Text + "/" + txtRangePara.Text;

                    if (ft.SubServico != null)
                    {
                        tbi.Flag = "SubServ";
                    }
                    else if (ft.Trf_Tours.Equals("TRF"))
                    {
                        tbi.Flag = "TRANSFER";
                    }
                    else
                    {
                        tbi.Flag = "TOUR";
                    }

                    //Supplier sp = spd.ObterPorId(Convert.ToInt32(ft.S_id));

                    //S_Servicos ss = servDal.ObterPorNome(ft.Transf_nome.Trim());

                    S_Servicos ss;

                    if (ft.Trf_CID_id != null)
                    {
                        ss = servDal.ObterPorNome(ft.Transf_nome.Trim(), Convert.ToInt32(ft.Trf_CID_id));
                    }
                    else
                    {
                        ss = servDal.ObterPorNome(ft.Transf_nome.Trim());
                    }

                    tbi.Cidade = ss.Cidade.CID_nome; // sp.Cidade.CID_nome;

                    tbid.Salvar(tbi);

                    soma = soma + Convert.ToDecimal(tbi.Range01);
                }

                if (fsed.ListarTodosRangeZero(IdQuote).Count() != 0)
                {

                    foreach (File_ServExtra ft in fsed.ListarTodosRangeZero(IdQuote))
                    {
                        TBItinerary tbi = new TBItinerary();

                        Quotation_TourMap qtm = new Quotation_TourMapDAL().ObterPorQuotationGrupoID(Convert.ToInt32(Session["SSIdQuotGrupo"]));

                        if (qtm != null)
                        {
                            tbi.tourmap = qtm.tourMap_Path;
                        }

                        tbi.Code = Code;
                        tbi.SuppNome = ft.S_nome;
                        tbi.ServExtrNome = ft.File_ServExtra_nome;
                        tbi.DateFrom = ft.Data_From;
                        tbi.DateTo = ft.Data_To;
                        tbi.Flag = "EXTRA";
                        tbi.S_id = ft.S_id;

                        tbi.idTabela = ft.File_ServExtra_id;
                        tbi.Quotation_Code = Session["Quotation_Code"].ToString();

                        tbi.Ordem = ft.Ordem;

                        if (ft.Flights_id != null)
                        {
                            FileFlightsDAL ffd = new FileFlightsDAL();

                            File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ft.Flights_id));

                            tbi.Flight_voo = ff.Flights_nome;
                            tbi.Flight_hora = ff.Flights_hora;
                            tbi.Flight_pickUp = ff.Flights_pickUp;
                        }

                        //if (Convert.ToInt32(txtRangeDe.Text.Trim()) <= ft.Paying_Pax)
                        //{
                        //tbi.Range01 = ft.File_ServExtra_venda;

                        tbi.Range01 = ft.File_ServExtra_vendaNet;

                        ////tbi.Range01 = ft.File_ServExtra_total;   
                        //}
                        //else
                        //{

                        //    Dictionary<int, decimal> ValoresExtras = (Dictionary<int, decimal>)Session["ValoresExtras"];

                        //    int IdTabela = Convert.ToInt32(ft.File_ServExtra_id);

                        //    decimal total = ValoresExtras[IdTabela];

                        //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                        //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                        //    decimal addMark = ((total * MarkupCliente) / 100) + total;
                        //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                        //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        //    {
                        //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                        //        Supplier spp = spd.ObterPorId(Convert.ToInt32(ft.S_id));
                        //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.Markup)) / 100) + addDesc;
                        //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                        //        tbi.Range01 = addDescNet;
                        //    }
                        //    else
                        //    {
                        //        tbi.Range01 = addDesc;
                        //    }

                        //}

                        //tbi.Base01 = txtRangeDe.Text + "/" + txtRangePara.Text;



                        Supplier sp = spd.ObterPorId(Convert.ToInt32(ft.S_id));

                        //S_Servicos ss = servDal.ObterPorNome(ft.File_ServExtra_nome.Trim());

                        tbi.Cidade = sp.Cidade.CID_nome;

                        //tbi.Cidade = sp.Cidade.CID_nome;

                        tbid.Salvar(tbi);

                        soma = soma + Convert.ToDecimal(tbi.Range01);
                    }
                }

                drw["Price"] = soma.ToString("N2");

                dummy.Rows.Add(drw);

                Session.Add("DataTableQuote", dummy);

                PopulaGridRanges(Code);

                NumRange = 2;

                List<TBItinerary> listaTBI = tbid.ListarTodosCode(Code);

                DateTime dataInicio = Convert.ToDateTime(listaTBI.First().DateFrom);

                int i = 1;

                foreach (TBItinerary tbiItiner in listaTBI)
                {
                    TBItinerary tbiIty = new TBItinerary();

                    if (tbiItiner.DateFrom != dataInicio)
                    {
                        double difer = (Convert.ToDateTime(tbiItiner.DateFrom) - Convert.ToDateTime(dataInicio)).TotalDays;

                        i = i + Convert.ToInt32(difer);
                        dataInicio = Convert.ToDateTime(tbiItiner.DateFrom);
                    }

                    tbiIty.DAY = i;
                    tbiIty.Itinerary_id = tbiItiner.Itinerary_id;

                    tbid.AtualizarDAY(tbiIty);
                }


                dlNomesQuote.DataSource = tbid.ListarTodosCode(Code);
                dlNomesQuote.DataBind();

                //btnOrdenar.Visible = true;

                dlQuote.DataSource = tbid.ListarTodosCode(Code);
                dlQuote.DataBind();

                FlagFirst = "N";
                ChangeDlQuote();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void MontaSeguintes()
        {
            try
            {
                CidadeDAL cd = new CidadeDAL();
                SupplierDAL spd = new SupplierDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL fts = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                TBItineraryDAL tbid = new TBItineraryDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                TarifaDAL tard = new TarifaDAL();
                MontaServicoDAL msd = new MontaServicoDAL();
                TarifCategoriaDAL tcategd = new TarifCategoriaDAL();
                CambioDAL cambDal = new CambioDAL();
                SBaseValorDAL sbaseV = new SBaseValorDAL();
                MoedaDAL mod = new MoedaDAL();

                int IdQuote = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;

                DataTable dummy = (DataTable)Session["DataTableQuote"];

                Moeda moedaQ = mod.ObterPorId(Convert.ToInt32(Session["IdMoedaQuote"]));
                MoedaQuote = moedaQ.Moeda_sigla;

                DataRow drw = dummy.NewRow();
                //drw["Base"] = txtRangeDe.Text + " to " + txtRangePara.Text + ")";
                //drw["Room"] = "Total per person in " + ddlRooms.SelectedItem + " (Travelers from ";


                List<TBItinerary> listatbiHtl = tbid.ListarTodosHOTEL(ViewState["Code"].ToString());

                List<TBItinerary> listatbiTrf = tbid.ListarTodosTRANSFER(ViewState["Code"].ToString());

                List<TBItinerary> listatbiTur = tbid.ListarTodosTOUR(ViewState["Code"].ToString());

                List<TBItinerary> listatbiExt = tbid.ListarTodosEXTRA(ViewState["Code"].ToString());

                decimal soma = 0;

                foreach (TBItinerary item in listatbiHtl)
                {

                    TBItinerary tb = new TBItinerary();

                    decimal total;

                    if (item.MealNome == null)
                    {

                        int IdCategoria = tcategd.ObterPorNome(item.Categoria).Tarif_categoria_id;

                        //S_Mercado_Tarifa smtarifa = tard.ListarTodosHoteisTarifasLista(Convert.ToDateTime(item.DateFrom),
                        //                                                               Convert.ToDateTime(item.DateTo),
                        //                                                               Convert.ToInt32(item.S_id),
                        //                                                               Convert.ToInt32(ddlRooms.SelectedValue),
                        //                                                               Convert.ToInt32(IdCategoria));

                        //if (!item.Room.ToString().Equals(ddlRooms.SelectedItem.ToString()))
                        //{

                        //    //decimal total;

                        //    if (smtarifa.S_Mercado_Periodo.Moeda_id != Convert.ToInt32(Session["IdMoedaQuote"]))
                        //    {
                        //        Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(smtarifa.S_Mercado_Periodo.Moeda_id), Convert.ToInt32(Session["IdMoedaQuote"]));

                        //        decimal valor = Convert.ToDecimal(smtarifa.S_merc_tarif_tarifa_total);

                        //        decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                        //        decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                        //        decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                        //        decimal addMark = ((valorComCambio * MarkupCliente) / 100) + valorComCambio;

                        //        decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                        //        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        //        {
                        //            MarkupPaisDAL mkd = new MarkupPaisDAL();

                        //            Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                        //            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        //            decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.Markup)) / 100) + addDesc;
                        //            decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                total = Convert.ToDecimal(addDescNet / smtarifa.Tipo_Room.Tipo_room_number);
                        //            }
                        //            else
                        //            {
                        //                total = addDescNet;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                total = Convert.ToDecimal(addDesc / smtarifa.Tipo_Room.Tipo_room_number);
                        //            }
                        //            else
                        //            {
                        //                total = addDesc;
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                        //        decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                        //        decimal addMark = ((Convert.ToDecimal(smtarifa.S_merc_tarif_tarifa_total) * MarkupCliente) / 100) + Convert.ToDecimal(smtarifa.S_merc_tarif_tarifa_total);

                        //        decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                        //        if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                        //        {
                        //            MarkupPaisDAL mkd = new MarkupPaisDAL();

                        //            Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                        //            MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        //            decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.Markup)) / 100) + addDesc;
                        //            decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                total = Convert.ToDecimal(addDescNet / smtarifa.Tipo_Room.Tipo_room_number);
                        //            }
                        //            else
                        //            {
                        //                total = addDescNet;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (smtarifa.S_merc_tarif_porApartamento == true)
                        //            {
                        //                total = Convert.ToDecimal(addDesc / smtarifa.Tipo_Room.Tipo_room_number);
                        //            }
                        //            else
                        //            {
                        //                total = addDesc;
                        //            }

                        //        }
                        //    }

                        //}
                        //else
                        //{
                        //if (smtarifa.S_merc_tarif_porApartamento == true)
                        //{
                        //    total = Convert.ToDecimal(item.Range01 / smtarifa.Tipo_Room.Tipo_room_number);
                        //}
                        //else
                        //{
                        //    total = Convert.ToDecimal(item.Range01);
                        //}

                        total = Convert.ToDecimal(item.Range01);
                        //}

                    }
                    else
                    {

                        total = Convert.ToDecimal(item.Range01);
                    }

                    switch (NumRange)
                    {
                        case 2:
                            tb.Range02 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base02 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 3:
                            tb.Range03 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base03 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 4:
                            tb.Range04 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base04 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 5:
                            tb.Range05 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base05 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 6:
                            tb.Range06 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base06 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 7:
                            tb.Range07 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base07 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 8:
                            tb.Range08 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base08 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                    }


                    tb.Itinerary_id = item.Itinerary_id;

                    tbid.Atualizar(tb, NumRange);
                }


                //-----------------------------------------------------------------------


                foreach (TBItinerary item in listatbiTrf)
                {

                    TBItinerary tb = new TBItinerary();

                    int IdMoeda = 0;
                    decimal tarifa = 0;
                    decimal total = 0;

                    string[] BaseDe = item.Base01.ToString().Split('/');

                    //if (Convert.ToInt32(txtRangeDe.Text.Trim()) == Convert.ToInt32(BaseDe[0]))
                    //{

                    tarifa = Convert.ToDecimal(item.Range01);
                    total = tarifa;
                    //}
                    //else
                    //{

                    //if (item.Flag.Equals("SubServ"))
                    //{
                    //    S_Bases_Valor sbv = sbaseV.ObterValorSub(Convert.ToInt32(item.S_id),
                    //                                             item.ServNome,
                    //                                             Convert.ToDateTime(item.DateFrom),
                    //                                             Convert.ToDateTime(item.DateTo),
                    //                                             Convert.ToInt32(txtRangeDe.Text));
                    //    IdMoeda = sbv.S_Bases.Moeda_id;
                    //    tarifa = Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                    //}
                    //else
                    //{
                    //    Monta_Servico_Valores msvv = msd.ObterValorTransfers(Convert.ToDateTime(item.DateFrom),
                    //                                                         Convert.ToDateTime(item.DateTo),
                    //                                                         Convert.ToInt32(item.S_id),
                    //                                                         Convert.ToInt32(txtRangeDe.Text),
                    //                                                         item.ServNome);
                    //    IdMoeda = msvv.S_Bases.Moeda_id;
                    //    tarifa = Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                    //}

                    //if (IdMoeda != Convert.ToInt32(Session["IdMoedaQuote"]))
                    //{
                    //    Cambio camb = cambDal.ObterPorIdMoedaPara(Convert.ToInt32(IdMoeda), Convert.ToInt32(Session["IdMoedaQuote"]));

                    //    decimal valor = Convert.ToDecimal(tarifa);

                    //    decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                    //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    //    decimal addMark = ((valorComCambio * MarkupCliente) / 100) + valorComCambio;

                    //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                    //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    //    {
                    //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                    //        Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                    //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                    //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                    //        total = addDescNet;
                    //    }
                    //    else
                    //    {
                    //        total = addDesc;
                    //    }
                    //}
                    //else
                    //{
                    //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    //    decimal addMark = ((Convert.ToDecimal(tarifa) * MarkupCliente) / 100) + Convert.ToDecimal(tarifa);

                    //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                    //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    //    {
                    //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                    //        Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                    //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                    //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                    //        total = addDescNet;
                    //    }
                    //    else
                    //    {
                    //        total = addDesc;
                    //    }
                    //}

                    //}

                    switch (NumRange)
                    {
                        case 2:
                            tb.Range02 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base02 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 3:
                            tb.Range03 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base03 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 4:
                            tb.Range04 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base04 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 5:
                            tb.Range05 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base05 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 6:
                            tb.Range06 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base06 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 7:
                            tb.Range07 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base07 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 8:
                            tb.Range08 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base08 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                    }

                    tb.Itinerary_id = item.Itinerary_id;
                    tbid.Atualizar(tb, NumRange);
                }


                //-----------------------------------------------------------------------


                foreach (TBItinerary item in listatbiTur)
                {

                    TBItinerary tb = new TBItinerary();

                    int IdMoeda = 0;
                    decimal tarifa = 0;
                    decimal total = 0;

                    string[] BaseDe = item.Base01.ToString().Split('/');

                    //if (Convert.ToInt32(txtRangeDe.Text.Trim()) == Convert.ToInt32(BaseDe[0]))
                    //{

                    //    tarifa = Convert.ToDecimal(item.Range01);
                    //    total = tarifa;
                    //}
                    //else
                    //{
                    //if (item.Flag.Equals("SubServ"))
                    //{
                    //    S_Bases_Valor sbv = sbaseV.ObterValorSub(Convert.ToInt32(item.S_id),
                    //                                             item.ServNome,
                    //                                             Convert.ToDateTime(item.DateFrom),
                    //                                             Convert.ToDateTime(item.DateTo),
                    //                                             Convert.ToInt32(txtRangeDe.Text));
                    //    IdMoeda = sbv.S_Bases.Moeda_id;
                    //    tarifa = Convert.ToDecimal(sbv.S_Bases_Valor_valor);
                    //}
                    //else
                    //{
                    //    Monta_Servico_Valores msvv = msd.ObterValorTransfers(Convert.ToDateTime(item.DateFrom),
                    //                                                         Convert.ToDateTime(item.DateTo),
                    //                                                         Convert.ToInt32(item.S_id),
                    //                                                         Convert.ToInt32(txtRangeDe.Text),
                    //                                                         item.ServNome);
                    //    IdMoeda = msvv.S_Bases.Moeda_id;
                    //    tarifa = Convert.ToDecimal(msvv.MServico_Valores_Bulk_Total);
                    //}

                    ////decimal total;

                    //if (IdMoeda != Convert.ToInt32(Session["IdMoedaQuote"]))
                    //{
                    //    Cambio camb = cambDal.ObterPorIdMoedaPara(IdMoeda, Convert.ToInt32(Session["IdMoedaQuote"]));

                    //    decimal valor = Convert.ToDecimal(tarifa);

                    //    decimal valorComCambio = valor * Convert.ToDecimal(camb.Cambio1);

                    //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    //    decimal addMark = ((valorComCambio * MarkupCliente) / 100) + valorComCambio;

                    //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                    //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    //    {
                    //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                    //        Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                    //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                    //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                    //        total = addDescNet;
                    //    }
                    //    else
                    //    {
                    //        total = addDesc;
                    //    }
                    //}
                    //else
                    //{
                    //    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    //    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    //    decimal addMark = ((Convert.ToDecimal(tarifa) * MarkupCliente) / 100) + Convert.ToDecimal(tarifa);

                    //    decimal addDesc = addMark - ((addMark * DescontoCliente) / 100);

                    //    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    //    {
                    //        MarkupPaisDAL mkd = new MarkupPaisDAL();

                    //        Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                    //        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                    //        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                    //        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                    //        total = addDescNet;
                    //    }
                    //    else
                    //    {
                    //        total = addDesc;
                    //    }
                    //}

                    //}

                    switch (NumRange)
                    {
                        case 2:
                            tb.Range02 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base02 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 3:
                            tb.Range03 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base03 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 4:
                            tb.Range04 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base04 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 5:
                            tb.Range05 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base05 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 6:
                            tb.Range06 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base06 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 7:
                            tb.Range07 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base07 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 8:
                            tb.Range08 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base08 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                    }

                    tb.Itinerary_id = item.Itinerary_id;
                    tbid.Atualizar(tb, NumRange);
                }


                //----------------------------------------------------------------------------


                foreach (TBItinerary item in listatbiExt)
                {

                    TBItinerary tb = new TBItinerary();

                    decimal total = 0;

                    string[] BaseDe = item.Base01.ToString().Split('/');

                    //if (Convert.ToInt32(txtRangeDe.Text.Trim()) == Convert.ToInt32(BaseDe[0]))
                    //{
                    //    tb.Range01 = item.Range01; // ft.File_ServExtra_venda;
                    //}
                    //else
                    //{

                    Dictionary<int, decimal> ValoresExtras = (Dictionary<int, decimal>)Session["ValoresExtras"];

                    int IdTabela = Convert.ToInt32(item.idTabela);

                    decimal MarkupCliente = Convert.ToDecimal(Session["MarkupQuote"]);
                    decimal DescontoCliente = Convert.ToDecimal(Session["DescontoQuote"]);

                    decimal addMark = ((ValoresExtras[IdTabela] * MarkupCliente) / 100) + ValoresExtras[IdTabela];

                    decimal subt = (addMark * DescontoCliente) / 100;

                    decimal addDesc = addMark - subt;

                    if (ConfigurationManager.AppSettings["FilePuxaMarkup"].Equals("Y"))
                    {
                        MarkupPaisDAL mkd = new MarkupPaisDAL();

                        Supplier spp = spd.ObterPorId(Convert.ToInt32(item.S_id));
                        MarkupPais mkp = mkd.ObterPorPais(Convert.ToInt32(spp.PAIS_id));

                        decimal addMarkNet = ((addDesc * Convert.ToDecimal(mkp.MarkupServ)) / 100) + addDesc;
                        decimal addDescNet = addMarkNet - ((addMarkNet * Convert.ToDecimal(mkp.Desconto)) / 100);

                        total = addDescNet;
                    }
                    else
                    {
                        total = addDesc;
                    }
                    //}

                    switch (NumRange)
                    {
                        case 2:
                            tb.Range02 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base02 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 3:
                            tb.Range03 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base03 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 4:
                            tb.Range04 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base04 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 5:
                            tb.Range05 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base05 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 6:
                            tb.Range06 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base06 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 7:
                            tb.Range07 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base07 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                        case 8:
                            tb.Range08 = total;
                            soma = soma + Convert.ToDecimal(total);
                            //tb.Base08 = txtRangeDe.Text + "/" + txtRangePara.Text;
                            break;
                    }

                    tb.Itinerary_id = item.Itinerary_id;
                    tbid.Atualizar(tb, NumRange);
                }

                drw["Price"] = soma.ToString("N2");

                dummy.Rows.Add(drw);

                Session.Add("DataTableQuote", dummy);

                PopulaGridRanges(ViewState["Code"].ToString());

                NumRange = NumRange + 1;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void MontaSeguintesNewFile()
        {
            try
            {
                CidadeDAL cd = new CidadeDAL();
                SupplierDAL spd = new SupplierDAL();
                FileTarifasDAL ftd = new FileTarifasDAL();
                FileTransfersDAL fts = new FileTransfersDAL();
                FileServExtraDAL fsed = new FileServExtraDAL();
                TBItineraryDAL tbid = new TBItineraryDAL();
                FileCarrinhoDAL fcd = new FileCarrinhoDAL();
                TarifaDAL tard = new TarifaDAL();
                MontaServicoDAL msd = new MontaServicoDAL();
                MoedaDAL mod = new MoedaDAL();
                CambioDAL cambDal = new CambioDAL();
                SBaseValorDAL sbaseV = new SBaseValorDAL();
                ServicoDAL servDal = new ServicoDAL();
                RangeDal rd = new RangeDal();

                string Code = GerarCode();

                ViewState["Code"] = Code;

                int IdFile = fcd.ObterPorIdGrupo(Convert.ToInt32(Session["SSIdQuotGrupo"])).File_id;
                int IdQuote = fcd.RetornaQuote(IdFile);
                int OptQuote = Convert.ToInt32(Request.QueryString["optQuote"]);

                decimal soma = 0;

                Moeda moedaQ = mod.ObterPorId(Convert.ToInt32(Session["IdMoedaQuote"]));
                MoedaQuote = moedaQ.Moeda_sigla;

                int qtdBases = rd.QtdBases(IdQuote, OptQuote);

                string[] bases = new string[qtdBases];

                int i = 0;

                foreach (string item in rd.RetornaTodasBases(IdQuote, OptQuote))
                {
                    bases[i] = item;
                    i++;
                }

                i = 0;

                string[] basesT = bases[i].ToString().Split('/');
                string baseDe = basesT[0];
                string baseAte = basesT[1];

                foreach (Ranges item in rd.ObterPorTarifaDeAteOpt(IdQuote, baseDe, baseAte, OptQuote))
                {

                    switch (item.Flag)
                    {
                        case "hotel":

                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(item.FileTabelaId));
                            TBItinerary tbi = new TBItinerary();

                            tbi.Code = Code;
                            tbi.DateFrom = ft.Data_From;
                            tbi.DateTo = ft.Data_To;
                            tbi.SuppNome = ft.S_nome;

                            if (Convert.ToBoolean(ft.Meal))
                            {
                                tbi.Flag = "MEAL";

                                if (ft.S_meal_status != null)
                                {
                                    tbi.MealNome = ft.S_meal_nome + " " + ft.S_meal_status;
                                }
                                else
                                {
                                    tbi.MealNome = ft.S_meal_nome;
                                }
                            }
                            else
                            {
                                tbi.Room = ft.Room;
                                tbi.Categoria = ft.Categoria;

                                tbi.Flag = "HOTEL";
                                tbi.NomePacote = ft.NomePacote;
                            }
                            tbi.S_id = ft.S_id;
                            tbi.idTabela = ft.File_Tarifas_id;
                            tbi.Quotation_Code = Session["Quotation_Code"].ToString();
                            tbi.Ordem = ft.Ordem;

                            Supplier sp = spd.ObterPorId(Convert.ToInt32(ft.S_id));
                            tbi.Cidade = sp.Cidade.CID_nome;

                            if (ft.Flights_id != null)
                            {
                                FileFlightsDAL ffd = new FileFlightsDAL();
                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ft.Flights_id));
                                tbi.Flight_voo = ff.Flights_nome;
                                tbi.Flight_hora = ff.Flights_hora;
                                tbi.Flight_pickUp = ff.Flights_pickUp;
                            }

                            tbid.Salvar(tbi);

                            foreach (Ranges rangesHoteis in rd.ObterPorTarifaDeAteOptItensOrdem(IdQuote, OptQuote, ft.File_Tarifas_id, "hotel"))
                            {
                                tbid.Atualizar(RetornaRange(i), RetornaBase(i), Convert.ToDecimal(rangesHoteis.ValorTotal), rangesHoteis.Ranges_de + "/" + rangesHoteis.Ranges_ate, tbi.Itinerary_id);
                                i++;
                            }

                            i = 0;

                            break;

                        case "servico":

                            File_Transfers ftr = fts.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                            TBItinerary tbii = new TBItinerary();

                            tbii.Code = Code;
                            tbii.ServNome = ftr.Transf_nome;
                            tbii.DateFrom = ftr.Data_From;
                            tbii.DateTo = ftr.Data_To;
                            tbii.S_id = ftr.S_id;
                            tbii.idTabela = ftr.File_Transf_id;
                            tbii.Quotation_Code = Session["Quotation_Code"].ToString();
                            tbii.Ordem = ftr.Ordem;

                            if (ftr.Flights_id != null)
                            {
                                FileFlightsDAL ffd = new FileFlightsDAL();

                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ftr.Flights_id));

                                tbii.Flight_voo = ff.Flights_nome;
                                tbii.Flight_hora = ff.Flights_hora;
                                tbii.Flight_pickUp = ff.Flights_pickUp;
                            }

                            if (ftr.SubServico != null)
                            {
                                tbii.Flag = "SubServ";
                            }
                            else if (ftr.Trf_Tours.Equals("TRF"))
                            {
                                tbii.Flag = "TRANSFER";
                            }
                            else
                            {
                                tbii.Flag = "TOUR";
                            }

                            S_Servicos ss;

                            if (ftr.Trf_CID_id != null)
                            {
                                ss = servDal.ObterPorNome(ftr.Transf_nome.Trim(), Convert.ToInt32(ftr.Trf_CID_id));
                            }
                            else
                            {
                                ss = servDal.ObterPorNome(ftr.Transf_nome.Trim());
                            }

                            tbii.Cidade = ss.Cidade.CID_nome;

                            tbid.Salvar(tbii);

                            foreach (Ranges rangesHoteis in rd.ObterPorTarifaDeAteOptItensOrdem(IdQuote, OptQuote, ftr.File_Transf_id, "servico"))
                            {
                                tbid.Atualizar(RetornaRange(i), RetornaBase(i), Convert.ToDecimal(rangesHoteis.ValorTotal), rangesHoteis.Ranges_de + "/" + rangesHoteis.Ranges_ate, tbii.Itinerary_id);
                                i++;
                            }

                            i = 0;

                            break;

                        case "extra":

                            File_ServExtra ftsx = fsed.ObterPorId(Convert.ToInt32(item.FileTabelaId));

                            TBItinerary tbi3 = new TBItinerary();

                            tbi3.Code = Code;
                            tbi3.SuppNome = ftsx.S_nome;
                            tbi3.ServExtrNome = ftsx.File_ServExtra_nome;
                            tbi3.DateFrom = ftsx.Data_From;
                            tbi3.DateTo = ftsx.Data_To;
                            tbi3.Flag = "EXTRA";
                            tbi3.S_id = ftsx.S_id;
                            tbi3.idTabela = ftsx.File_ServExtra_id;
                            tbi3.Quotation_Code = Session["Quotation_Code"].ToString();

                            tbi3.Ordem = ftsx.Ordem;

                            if (ftsx.Flights_id != null)
                            {
                                FileFlightsDAL ffd = new FileFlightsDAL();

                                File_Flights ff = ffd.ObterPorId(Convert.ToInt32(ftsx.Flights_id));

                                tbi3.Flight_voo = ff.Flights_nome;
                                tbi3.Flight_hora = ff.Flights_hora;
                                tbi3.Flight_pickUp = ff.Flights_pickUp;
                            }

                            Supplier spp = spd.ObterPorId(Convert.ToInt32(ftsx.S_id));

                            tbi3.Cidade = spp.Cidade.CID_nome;

                            tbid.Salvar(tbi3);

                            foreach (Ranges rangesHoteis in rd.ObterPorTarifaDeAteOptItensOrdem(IdQuote, OptQuote, ftsx.File_ServExtra_id, "extra"))
                            {
                                tbid.Atualizar(RetornaRange(i), RetornaBase(i), Convert.ToDecimal(rangesHoteis.ValorTotal), rangesHoteis.Ranges_de + "/" + rangesHoteis.Ranges_ate, tbi3.Itinerary_id);
                                i++;
                            }

                            i = 0;

                            break;
                    }
                }

                DataTable dummy = new DataTable();
                dummy.Columns.Add("Room");
                dummy.Columns.Add("Base");
                dummy.Columns.Add("Price");

                int qtdRooms = tbid.QtdRooms(Code);
                string[] rooms = new string[qtdRooms];

                int k = 0;

                foreach (string nome in tbid.ObterRoomsCode(Code))
                {
                    rooms[k] = nome;
                    k++;
                }

                k = 0;

                for (int l = 0; l < qtdBases; l++)
                {

                    for (int ro = 0; ro < rooms.Length; ro++)
                    {
                        decimal somatorio = SomaDasBases(Code, rooms, k, l);
                        DataRow drw = dummy.NewRow();
                        switch (rooms[k])
                        {
                            case "Single":
                                drw["Room"] = "Total per person in Single (Travelers from ";
                                drw["Base"] = bases[l] + ")";
                                drw["Price"] = somatorio.ToString("N2");
                                break;
                            case "Double":
                                drw["Room"] = "Total per person in Double (Travelers from ";
                                drw["Base"] = bases[l] + ")";
                                drw["Price"] = somatorio.ToString("N2");
                                break;
                            case "Triple":
                                drw["Room"] = "Total per person in Triple (Travelers from ";
                                drw["Base"] = bases[l] + ")";
                                drw["Price"] = somatorio.ToString("N2");
                                break;
                        }
                        dummy.Rows.Add(drw);

                        if (rooms.Length > 1)
                        {
                            k++;
                        }
                    }
                    k = 0;
                }

                ViewState["qtdRooms"] = rooms.Count();
                Session.Add("DataTableQuote", dummy);

                PopulaGridRanges(Code);

                List<TBItinerary> listaTBI = new TBItineraryDAL().ListarTodosCode(Code);

                DateTime dataInicio = Convert.ToDateTime(listaTBI.First().DateFrom);

                int j = 1;

                foreach (TBItinerary tbiItiner in listaTBI)
                {
                    TBItinerary tbiIty = new TBItinerary();

                    if (tbiItiner.DateFrom != dataInicio)
                    {
                        double difer = (Convert.ToDateTime(tbiItiner.DateFrom) - Convert.ToDateTime(dataInicio)).TotalDays;

                        j = j + Convert.ToInt32(difer);
                        dataInicio = Convert.ToDateTime(tbiItiner.DateFrom);
                    }

                    tbiIty.DAY = j;
                    tbiIty.Itinerary_id = tbiItiner.Itinerary_id;

                    tbid.AtualizarDAY(tbiIty);
                }


                dlNomesQuote.DataSource = tbid.ListarTodosCode(Code);
                dlNomesQuote.DataBind();

                //btnOrdenar.Visible = true;

                dlQuote.DataSource = new TBItineraryDAL().ListarTodosCode(Code);
                dlQuote.DataBind();

                FlagFirst = "N";
                ChangeDlQuote();

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected decimal SomaDasBases(string Code, string[] rooms, int k, int bases)
        {

            TBItineraryDAL tbid = new TBItineraryDAL();
            SqlCon con = new SqlCon();
            decimal retorno = 0;

            try
            {
                string sql = "SELECT Itinerary_id, Code, idTabela, Quotation_Code, SuppNome, S_id, ServNome, ServExtrNome, DateFrom, DateTo, Cidade, Categoria, Room, Flag, Flight_voo, Flight_hora, Flight_pickUp, Ordem, ";
                sql = sql + "NomePacote, MealNome, DAY, Range01, Base01, Range02, Base02, Range03, Base03, Range04, Base04, Range05, Base05, Range06, Base06, Range07, Base07, Range08, Base08, Range09, ";
                sql = sql + "Base09, Range10, Base10, Range11, Base11, Range12, Base12, Range13, Base13, Range14, Base14, Range15, Base15, Range16, Base16, Range17, Base17 ";
                sql = sql + "FROM TBItinerary WHERE (Code = @p1) ORDER BY DateFrom, Ordem ";

                con.AbrirConexao();
                con.Cmd = new SqlCommand(sql, con.Con);
                con.Cmd.Parameters.AddWithValue("@p1", Code);
                con.Dr = con.Cmd.ExecuteReader();

                decimal somatorio = 0;

                while (con.Dr.Read())
                {
                    if (con.Dr["Flag"].ToString().Equals("HOTEL") || con.Dr["Flag"].ToString().Equals("MEAL"))
                    {
                        File_Tarifas ft = new FileTarifasDAL().ObterPorId(Convert.ToInt32(con.Dr["idTabela"]));

                        if (ft.TBulk == true)
                        {
                            if (rooms[k].Equals(ft.Room))
                            {
                                somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                                somatorio = Math.Round(somatorio, 2);
                            }
                        }
                        else
                        {
                            if (rooms[k].Equals(ft.Room))
                            {
                                somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                            }

                            if (ft.Meal == true && ft.S_meal_status == null)
                            {
                                somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                            }
                        }
                    }
                    else if (con.Dr["Flag"].ToString().Equals("TRANSFER") || con.Dr["Flag"].ToString().Equals("TOUR") || con.Dr["Flag"].ToString().Equals("SubServ"))
                    {
                        File_Transfers ftrans = new FileTransfersDAL().ObterPorId(Convert.ToInt32(con.Dr["idTabela"]));

                        if (ftrans.TBulk == true)
                        {
                            somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                        }
                        else
                        {
                            somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                        }
                    }
                    else if (con.Dr["Flag"].ToString().Equals("EXTRA"))
                    {
                        File_ServExtra fservext = new FileServExtraDAL().ObterPorId(Convert.ToInt32(con.Dr["idTabela"]));

                        if (fservext.TBulk == true)
                        {
                            somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                        }
                        else
                        {
                            somatorio = somatorio + Convert.ToDecimal(con.Dr[RetornaRange(bases)]);
                        }
                    }

                    retorno = somatorio;
                }


                return retorno;

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return 0;
            }
            finally
            {
                con.FecharConexao();
            }
        }

        protected string RetornaRange(int bases)
        {
            string range = "";
            switch (bases)
            {
                case 0:
                    range = "Range01";
                    break;
                case 1:
                    range = "Range02";
                    break;
                case 2:
                    range = "Range03";
                    break;
                case 3:
                    range = "Range04";
                    break;
                case 4:
                    range = "Range05";
                    break;
                case 5:
                    range = "Range06";
                    break;
                case 6:
                    range = "Range07";
                    break;
                case 7:
                    range = "Range08";
                    break;
                case 8:
                    range = "Range09";
                    break;
                case 9:
                    range = "Range10";
                    break;
                case 10:
                    range = "Range11";
                    break;
                case 11:
                    range = "Range12";
                    break;
            }
            return range;
        }

        protected string RetornaBase(int bases)
        {
            string range = "";
            switch (bases)
            {
                case 0:
                    range = "Base01";
                    break;
                case 1:
                    range = "Base02";
                    break;
                case 2:
                    range = "Base03";
                    break;
                case 3:
                    range = "Base04";
                    break;
                case 4:
                    range = "Base05";
                    break;
                case 5:
                    range = "Base06";
                    break;
                case 6:
                    range = "Base07";
                    break;
                case 7:
                    range = "Base08";
                    break;
                case 8:
                    range = "Base09";
                    break;
                case 9:
                    range = "Base10";
                    break;
                case 10:
                    range = "Base11";
                    break;
                case 11:
                    range = "Base12";
                    break;
            }
            return range;
        }

        public string GerarCode()
        {
            int Tamanho = 10; // Numero de digitos da senha
            string senha = string.Empty;
            for (int i = 0; i < Tamanho; i++)
            {
                Random random = new Random();
                int codigo = Convert.ToInt32(random.Next(48, 122).ToString());

                if ((codigo >= 48 && codigo <= 57) || (codigo >= 97 && codigo <= 122))
                {
                    string _char = ((char)codigo).ToString();
                    if (!senha.Contains(_char))
                    {
                        senha += _char;
                    }
                    else
                    {
                        i--;
                    }
                }
                else
                {
                    i--;
                }
            }
            return senha;
        }

        protected void GeraTotais(string Code)
        {
            try
            {
                TBItineraryDAL tbid = new TBItineraryDAL();
                RangeDal rd = new RangeDal();

                DataTable dummy = new DataTable();
                dummy.Columns.Add("Room");
                dummy.Columns.Add("Base");
                dummy.Columns.Add("Price");

                TBItinerary tb = tbid.ListarTodosCode(Code).First();

                int OptQuote = Convert.ToInt32(Request.QueryString["optQuote"]);

                Quotation q = new QuotationDAL().ObterPorCode(tb.Quotation_Code);

                int qtdBases = rd.QtdBases(q.Quotation_Id, OptQuote);

                string[] bases = new string[qtdBases];

                int i = 0;

                foreach (string item in rd.RetornaTodasBases(q.Quotation_Id, OptQuote))
                {
                    bases[i] = item;
                    i++;
                }

                i = 0;

                string[] basesT = bases[i].ToString().Split('/');
                string baseDe = basesT[0];
                string baseAte = basesT[1];


                int qtdRooms = tbid.QtdRooms(Code);
                string[] rooms = new string[qtdRooms];

                int k = 0;

                foreach (string nome in tbid.ObterRoomsCode(Code))
                {
                    rooms[k] = nome;
                    k++;
                }

                k = 0;

                for (int l = 0; l < qtdBases; l++)
                {

                    for (int ro = 0; ro < rooms.Length; ro++)
                    {
                        decimal somatorio = SomaDasBases(Code, rooms, k, l);
                        DataRow drw = dummy.NewRow();
                        switch (rooms[k])
                        {
                            case "Single":
                                drw["Room"] = "Total per person in Single (Travelers from ";
                                drw["Base"] = bases[l] + ")";
                                drw["Price"] = somatorio.ToString("N2");
                                break;
                            case "Double":
                                drw["Room"] = "Total per person in Double (Travelers from ";
                                drw["Base"] = bases[l] + ")";
                                drw["Price"] = somatorio.ToString("N2");
                                break;
                            case "Triple":
                                drw["Room"] = "Total per person in Triple (Travelers from ";
                                drw["Base"] = bases[l] + ")";
                                drw["Price"] = somatorio.ToString("N2");
                                break;
                        }
                        dummy.Rows.Add(drw);

                        if (rooms.Length > 1)
                        {
                            k++;
                        }
                    }
                    k = 0;
                }

                ViewState["qtdRooms"] = rooms.Count();
                Session.Add("DataTableQuote", dummy);

                PopulaGridRanges(Code);

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void PopulaGridRanges(string Code)
        {
            try
            {
                TBItineraryDAL tbd = new TBItineraryDAL();
                DataTable dt = new DataTable();

                dt = (DataTable)Session["DataTableQuote"];

                #region comentado
                //if (Request.QueryString["Code"].Equals(""))
                //{
                //    dt = (DataTable)Session["DataTableQuote"];
                //}
                //else
                //{
                //    dt = (DataTable)Session["DataTableQuote"];

                //List<TBItinerary> lstIt = new TBItineraryDAL().ListarTodosCode(Code);

                //dt.Columns.Add("Room");
                //dt.Columns.Add("Base");
                //dt.Columns.Add("Price");

                //decimal somaServicos = 0;
                //decimal somaSingle = 0;
                //decimal somaDouble = 0;
                //decimal somaTriple = 0;

                //foreach (TBItinerary it in lstIt)
                //{

                //    if (it.Room == null)
                //    {
                //        somaServicos = somaServicos + Convert.ToDecimal(it.Range01);
                //    }

                //    if (it.Room == "Single")
                //    {
                //        if (it.Range01 != null)
                //            somaSingle = somaSingle + (decimal)it.Range01;
                //    }
                //    else if (it.Room == "Double")
                //    {
                //        if (it.Range01 != null)
                //            somaDouble = somaDouble + (decimal)it.Range01;
                //    }
                //    else if (it.Room == "Triple")
                //        if (it.Range01 != null)
                //            somaTriple = somaTriple + (decimal)it.Range01;
                //}

                //DataRow dr = dt.NewRow();

                //if (lstIt.Count(a => a.Room == "Single") > 0)
                //{
                //    somaSingle = somaSingle + somaServicos;
                //    dr["Room"] = "Total per person in Single (Travelers from";
                //    dr["Base"] = string.Format("{0} to {0}", lstIt[0].Base01.Substring(0, lstIt[0].Base01.IndexOf('/')));
                //    dr["Price"] = somaSingle.ToString("N2");
                //}
                //if (lstIt.Count(a => a.Room == "Double") > 0)
                //{
                //    somaDouble = somaDouble + somaServicos;
                //    dr["Room"] = "Total per person in Double (Travelers from";
                //    dr["Base"] = string.Format("{0} to {0}", lstIt[0].Base01.Substring(0, lstIt[0].Base01.IndexOf('/')));
                //    dr["Price"] = somaDouble.ToString("N2");
                //}
                //if (lstIt.Count(a => a.Room == "Triple") > 0)
                //{
                //    somaTriple = somaTriple + somaServicos;
                //    dr["Room"] = "Total per person in Triple (Travelers from";
                //    dr["Base"] = string.Format("{0} to {0}", lstIt[0].Base01.Substring(0, lstIt[0].Base01.IndexOf('/')));
                //    dr["Price"] = somaTriple.ToString("N2");
                //}


                //dt.Rows.Add(dr);

                //}
                #endregion

                DataListRates.DataSource = dt;
                DataListRates.DataBind();

                DataListRates.RepeatColumns = Convert.ToInt32(ViewState["qtdRooms"]);

                //GridRates.DataSource = dt;
                //GridRates.DataBind();

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnAddRange_Click(object sender, EventArgs e)
        {
            try
            {
                if (FlagFirst.Equals("S"))
                {
                    MontaEntrada();
                    FlagFirst = "N";
                    ChangeDlQuote();
                }
                else
                {
                    VerificaExtra();

                    if (ViewState["VerificaExtra"].Equals("N"))
                    {
                        MontaSeguintes();
                        ChangeDlQuote();
                    }
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void GridRates_DataBound(object sender, EventArgs e)
        {
            try
            {

                TBItineraryDAL tbi = new TBItineraryDAL();

                string soma = string.Empty;

                List<TBItinerary> listatbi = tbi.ListarTodosCode(ViewState["Code"].ToString());

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void ChangeDlQuote()
        {
            try
            {

                DescricaoDAL dd = new DescricaoDAL();
                FotoDAL fd = new FotoDAL();
                ServicoDAL servd = new ServicoDAL();
                CidadeDAL cd = new CidadeDAL();
                FotoServicoDAL fsd = new FotoServicoDAL();
                TBItineraryDAL tbd = new TBItineraryDAL();
                DescritivoPacoteDAL dpd = new DescritivoPacoteDAL();

                int i = 0;
                int descrExist = 0;

                foreach (DataListItem item in dlQuote.Items)
                {
                    Label lblFlag = (Label)item.FindControl("lblFlag");
                    Image imgIcon = (Image)item.FindControl("imgIcon");
                    Label lblSId = (Label)item.FindControl("lblSId");
                    Label lblDescricao = (Label)item.FindControl("lblDescricao");
                    Image imgPrincipal = (Image)item.FindControl("imgPrincipal");
                    Label lblNomeCidade = (Label)item.FindControl("lblNomeCidade");
                    Label lblServNome = (Label)item.FindControl("lblServNome");
                    Label lblTBItiId = (Label)item.FindControl("lblTBItiId");
                    Label lblServExtrNome = (Label)item.FindControl("lblServExtrNome");
                    Label lblSNome = (Label)item.FindControl("lblSNome");
                    Label lblFlight = (Label)item.FindControl("lblFlight");
                    Label lblHora = (Label)item.FindControl("lblHora");
                    Label lblTituloFlight = (Label)item.FindControl("lblTituloFlight");
                    Label lblTituloHora = (Label)item.FindControl("lblTituloHora");
                    Label lblDataFrom = (Label)item.FindControl("lblDataFrom");
                    Label lblDataTo = (Label)item.FindControl("lblDataTo");
                    Label lblNomePacote = (Label)item.FindControl("lblNomePacote");
                    Label lblDescricaoPacote = (Label)item.FindControl("lblDescricaoPacote");
                    Label lblMealNome = (Label)item.FindControl("lblMealNome");
                    Label lblNoites = (Label)item.FindControl("lblNoites");
                    Label lblContDia = (Label)item.FindControl("lblContDia");
                    Label lblDataDia = (Label)item.FindControl("lblDataDia");
                    Label lblContaDiaTexto = (Label)item.FindControl("lblContaDiaTexto");

                    System.Web.UI.HtmlControls.HtmlGenericControl divTituloQuote = (System.Web.UI.HtmlControls.HtmlGenericControl)item.FindControl("divTituloQuote");
                    System.Web.UI.HtmlControls.HtmlGenericControl divDescrGeral = (System.Web.UI.HtmlControls.HtmlGenericControl)item.FindControl("divDescrGeral");

                    Label lblBase01 = (Label)item.FindControl("lblBase01");
                    Label lblRange01 = (Label)item.FindControl("lblRange01");

                    Label lblBase02 = (Label)item.FindControl("lblBase02");
                    Label lblRange02 = (Label)item.FindControl("lblRange02");

                    Label lblBase03 = (Label)item.FindControl("lblBase03");
                    Label lblRange03 = (Label)item.FindControl("lblRange03");

                    Label lblBase04 = (Label)item.FindControl("lblBase04");
                    Label lblRange04 = (Label)item.FindControl("lblRange04");

                    Label lblBase05 = (Label)item.FindControl("lblBase05");
                    Label lblRange05 = (Label)item.FindControl("lblRange05");

                    Label lblBase06 = (Label)item.FindControl("lblBase06");
                    Label lblRange06 = (Label)item.FindControl("lblRange06");

                    Label lblBase07 = (Label)item.FindControl("lblBase07");
                    Label lblRange07 = (Label)item.FindControl("lblRange07");

                    Label lblBase08 = (Label)item.FindControl("lblBase08");
                    Label lblRange08 = (Label)item.FindControl("lblRange08");

                    //if (Convert.ToInt32(ddlTipoQuote.SelectedValue) == 1)
                    //{

                    //    switch (NumRange)
                    //    {
                    //        case 2:
                    //            TBItinerary t1 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase01.Text = t1.Base01;
                    //            lblRange01.Text = t1.Range01.ToString();
                    //            break;
                    //        case 3:
                    //            TBItinerary t2 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase02.Text = t2.Base02;
                    //            lblRange02.Text = t2.Range02.ToString();
                    //            break;
                    //        case 4:
                    //            TBItinerary t3 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase03.Text = t3.Base03;
                    //            lblRange03.Text = t3.Range03.ToString();
                    //            break;
                    //        case 5:
                    //            TBItinerary t4 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase04.Text = t4.Base04;
                    //            lblRange04.Text = t4.Range04.ToString();
                    //            break;
                    //        case 6:
                    //            TBItinerary t5 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase05.Text = t5.Base05;
                    //            lblRange05.Text = t5.Range05.ToString();
                    //            break;
                    //        case 7:
                    //            TBItinerary t6 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase06.Text = t6.Base06;
                    //            lblRange06.Text = t6.Range06.ToString();
                    //            break;
                    //        case 8:
                    //            TBItinerary t7 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase07.Text = t7.Base07;
                    //            lblRange07.Text = t7.Range07.ToString();
                    //            break;
                    //        case 9:
                    //            TBItinerary t8 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));
                    //            lblBase08.Text = t8.Base08;
                    //            lblRange08.Text = t8.Range08.ToString();
                    //            break;
                    //    }

                    //    lblBase01.Visible = true;
                    //    lblBase02.Visible = true;
                    //    lblBase03.Visible = true;
                    //    lblBase04.Visible = true;
                    //    lblBase05.Visible = true;
                    //    lblBase06.Visible = true;
                    //    lblBase07.Visible = true;
                    //    lblBase08.Visible = true;
                    //    lblRange01.Visible = true;
                    //    lblRange02.Visible = true;
                    //    lblRange03.Visible = true;
                    //    lblRange04.Visible = true;
                    //    lblRange05.Visible = true;
                    //    lblRange06.Visible = true;
                    //    lblRange07.Visible = true;
                    //    lblRange08.Visible = true;
                    //}
                    //else
                    //{
                    //    lblBase01.Visible = false;
                    //    lblBase02.Visible = false;
                    //    lblBase03.Visible = false;
                    //    lblBase04.Visible = false;
                    //    lblBase05.Visible = false;
                    //    lblBase06.Visible = false;
                    //    lblBase07.Visible = false;
                    //    lblBase08.Visible = false;
                    //    lblRange01.Visible = false;
                    //    lblRange02.Visible = false;
                    //    lblRange03.Visible = false;
                    //    lblRange04.Visible = false;
                    //    lblRange05.Visible = false;
                    //    lblRange06.Visible = false;
                    //    lblRange07.Visible = false;
                    //    lblRange08.Visible = false;
                    //}

                    if (!lblFlight.Text.Equals(""))
                    {
                        lblTituloFlight.Visible = true;
                        lblTituloHora.Visible = true;
                        lblFlight.Visible = true;
                        lblHora.Visible = true;
                    }
                    else
                    {
                        lblTituloFlight.Visible = false;
                        lblTituloHora.Visible = false;
                        lblFlight.Visible = false;
                        lblHora.Visible = false;
                    }

                    UrlEmpresa = ConfigurationManager.AppSettings["UrlEmpresa"].ToString();


                    //TBItinerary tbPrx = tbd.ObterPorId(

                    if (i == 0)
                    {
                        ViewState["idAnterior"] = lblTBItiId.Text;
                        i = i + 1;
                    }

                    if (!ViewState["idAnterior"].ToString().Equals(lblTBItiId.Text))
                    {

                        TBItinerary tbAnterior = tbd.ObterPorId(Convert.ToInt32(ViewState["idAnterior"]));
                        TBItinerary tbProx = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));

                        ViewState["idAnterior"] = lblTBItiId.Text;

                        if (tbAnterior.DAY == tbProx.DAY && tbAnterior.Cidade == tbProx.Cidade && tbAnterior.DateFrom == tbProx.DateFrom)
                        {

                            divTituloQuote.Style.Add("border-bottom", "thin dashed #d6d6d6");
                            divTituloQuote.Style.Add("float", "left");
                            divTituloQuote.Style.Add("height", "5px");
                            divTituloQuote.Style.Add("width", "835px");

                            lblContDia.Visible = false;
                            lblNomeCidade.Visible = false;
                            lblDataDia.Visible = false;
                            lblContaDiaTexto.Visible = false;
                        }
                        else
                        {

                            divTituloQuote.Style.Add("border-bottom", "thin dashed #d6d6d6");
                            divTituloQuote.Style.Add("float", "left");
                            divTituloQuote.Style.Add("height", "81px");
                            divTituloQuote.Style.Add("width", "835px");
                            divTituloQuote.Style.Add("margin-top", "20px");

                            lblContDia.Visible = true;
                            lblNomeCidade.Visible = true;
                            lblDataDia.Visible = true;
                            lblContaDiaTexto.Visible = true;
                        }


                        if (tbAnterior.DAY == tbProx.DAY && tbAnterior.Cidade == tbProx.Cidade && tbAnterior.DateFrom == tbProx.DateFrom && tbAnterior.SuppNome == tbProx.SuppNome && tbAnterior.Categoria == tbProx.Categoria)
                        {
                            descrExist = 1;
                            divDescrGeral.Style.Add("border-bottom", "0px");
                            divDescrGeral.Style.Add("float", "left");
                            divDescrGeral.Style.Add("width", "835px");
                            divDescrGeral.Style.Add("height", "0px");
                            divDescrGeral.Style.Add("margin-top", "5px");
                            divDescrGeral.Style.Add("margin-left", "0px");
                            divDescrGeral.Style.Add("margin-bottom", "10px");
                        }
                        else
                        {
                            descrExist = 0;
                            divDescrGeral.Style.Add("border-bottom", "1px solid #ebebeb");
                            divDescrGeral.Style.Add("float", "left");
                            divDescrGeral.Style.Add("width", "835px");
                            divDescrGeral.Style.Add("height", "auto");
                            divDescrGeral.Style.Add("margin-top", "5px");
                            divDescrGeral.Style.Add("margin-left", "0px");
                            divDescrGeral.Style.Add("margin-bottom", "10px");
                        }

                    }





                    if (!lblNomePacote.Text.Equals(""))
                    {
                        Descritivo_Pacote dpcote = dpd.ObterPacote(Convert.ToDateTime(lblDataFrom.Text), Convert.ToDateTime(lblDataTo.Text), Convert.ToInt32(lblSId.Text), lblNomePacote.Text.Trim());


                        lblDescricaoPacote.Visible = true;
                        lblNomePacote.Visible = true;

                        if (dpcote != null)
                        {
                            string DescricaoPac = "<br />";

                            DescricaoPac = DescricaoPac + "<b>Day 1</b><br/>";
                            DescricaoPac = DescricaoPac + dpcote.Descritivo_descr0;
                            DescricaoPac = DescricaoPac + "<br /><br />";

                            if (dpcote.Descritivo_descr1.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 2</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr1;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr2.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 3</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr2;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr3.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 4</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr3;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr4.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 5</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr4;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr5.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 6</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr5;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr6.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 7</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr6;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr7.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 8</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr7;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr8.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 9</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr8;
                                DescricaoPac = DescricaoPac + "<br /><br />";
                            }
                            if (dpcote.Descritivo_descr9.ToString() != "")
                            {
                                DescricaoPac = DescricaoPac + "<b>Day 10</b><br/>";
                                DescricaoPac = DescricaoPac + dpcote.Descritivo_descr9;
                            }

                            lblDescricaoPacote.Text = DescricaoPac;
                        }
                        else
                        {
                            lblDescricaoPacote.Text = "The package has no description.";
                        }
                    }



                    if (!lblSNome.Text.Equals(""))
                    {
                        TBItinerary t1 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));

                        double NumNoites = (Convert.ToDateTime(t1.DateTo) - Convert.ToDateTime(t1.DateFrom)).TotalDays;

                        lblNoites.Text = " - " + NumNoites + " Night(s)";

                        S_Descricao sd = dd.ObterPorIdSupp(Convert.ToInt32(lblSId.Text));

                        if (sd != null)
                        {
                            DivDescr = "block";

                            string descr = sd.Desc_short + "</br>" + sd.Desc_long;

                            if (descrExist == 0)
                            {
                                lblDescricao.Text = descr;
                            }
                        }
                        else
                        {
                            if (descrExist == 0)
                            {
                                lblDescricao.Text = "No description";
                            }
                        }

                        //if (ConfigurationManager.AppSettings["PuxaFotoQuote"].ToString().Equals("Y"))
                        if (Convert.ToInt32(Request.QueryString["foto"]) == 0)
                        {
                            S_Image si = fd.ObterPorSupplierCapa(Convert.ToInt32(lblSId.Text));

                            if (si != null)
                            {
                                DivDescr = "block";

                                if (descrExist == 0)
                                {
                                    imgPrincipal.Visible = true;
                                    imgPrincipal.CssClass = "ImgPrincipalPacoteHTL";

                                    string fotoReziseTemp = "/temp/" + si.Image_nome;
                                    string fotoResize = "/Galeria/" + lblSId.Text + "/" + si.Image_nome;

                                    ResizeFoto rf = new ResizeFoto();

                                    rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);


                                    imgPrincipal.ImageUrl = UrlEmpresa + fotoReziseTemp;
                                }
                            }
                            else
                            {
                                DivDescr = "block";

                                if (descrExist == 0)
                                {
                                    imgPrincipal.Visible = true;
                                    imgPrincipal.CssClass = "ImgPrincipalPacoteHTL";

                                    string fotoReziseTemp = "/temp/semimagem.jpg";
                                    string fotoResize = "/Galeria/semimagem.jpg";

                                    ResizeFoto rf = new ResizeFoto();

                                    rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);

                                    imgPrincipal.ImageUrl = UrlEmpresa + fotoReziseTemp;
                                }
                            }
                        }
                    }



                    if (!lblMealNome.Text.Equals(""))
                    {
                        imgPrincipal.Visible = false;
                        lblDescricao.Text = "";

                        TBItinerary t1 = tbd.ObterPorId(Convert.ToInt32(lblTBItiId.Text));

                        double NumNoites = (Convert.ToDateTime(t1.DateTo) - Convert.ToDateTime(t1.DateFrom)).TotalDays;

                        lblNoites.Text = " - " + NumNoites + " day(s)";

                        //lblSNome.Text = "";
                    }

                    if (!lblServExtrNome.Text.Equals(""))
                    {
                        lblNoites.Text = "";
                        lblSNome.Text = "";

                        S_Descricao sd = dd.ObterPorIdSupp(Convert.ToInt32(lblSId.Text));

                        if (sd != null)
                        {
                            DivDescr = "block";

                            string descr = sd.Desc_short + "</br>" + sd.Desc_long;

                            if (descrExist == 0)
                            {
                                lblDescricao.Text = descr;
                            }
                        }
                        else
                        {
                            if (descrExist == 0)
                            {
                                lblDescricao.Text = "No description";
                            }
                        }

                        ///if (ConfigurationManager.AppSettings["PuxaFotoQuote"].ToString().Equals("Y"))
                        if (Convert.ToInt32(Request.QueryString["foto"]) == 0)
                        {
                            S_Image si = fd.ObterPorSupplierCapa(Convert.ToInt32(lblSId.Text));

                            if (si != null)
                            {
                                DivDescr = "block";

                                if (descrExist == 0)
                                {
                                    imgPrincipal.Visible = true;
                                    imgPrincipal.CssClass = "ImgPrincipalPacoteHTL";

                                    string fotoReziseTemp = "/temp/" + si.Image_nome;
                                    string fotoResize = "/Galeria/" + lblSId.Text + "/" + si.Image_nome;

                                    ResizeFoto rf = new ResizeFoto();

                                    rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 242, 191);


                                    imgPrincipal.ImageUrl = UrlEmpresa + fotoReziseTemp;
                                }

                                //imgPrincipal.ImageUrl = UrlEmpresa + "/Galeria/" + lblSId.Text + "/" + si.Image_nome;
                            }
                            else
                            {
                                DivDescr = "block";

                                if (descrExist == 0)
                                {
                                    imgPrincipal.Visible = true;
                                    imgPrincipal.CssClass = "ImgPrincipalPacoteHTL";

                                    imgPrincipal.ImageUrl = UrlEmpresa + "/images/arrival.png";
                                }
                            }
                        }

                    }




                    if (!lblServNome.Text.Equals(""))
                    {
                        lblSNome.Text = "";
                        lblNoites.Text = "";

                        S_Servicos sserv = servd.ObterPorNome(lblServNome.Text, cd.ObterPorNome(lblNomeCidade.Text).CID_id);

                        if (sserv.Servicos_descr != null)
                        {
                            DivDescr = "block";

                            if (descrExist == 0)
                            {
                                lblDescricao.Text = sserv.Servicos_descr;
                            }
                        }
                        else
                        {
                            DivDescr = "block";

                            if (descrExist == 0)
                            {
                                lblDescricao.Text = "No description";
                            }
                        }

                        //if (ConfigurationManager.AppSettings["PuxaFotoQuote"].ToString().Equals("Y"))
                        if (Convert.ToInt32(Request.QueryString["foto"]) == 0)
                        {

                            Servicos_Imagem servImg = fsd.ObterImgPrincipal(sserv.Servicos_Id);

                            if (sserv.S_Servicos_Tipo_Categ.Tipo_categ_nome.Equals("Trasnfer In") || sserv.S_Servicos_Tipo_Categ.Tipo_categ_nome.Equals("Transfer Out"))
                            {
                                imgPrincipal.Visible = false;
                            }
                            else if (sserv.Servicos_transfer != null && servImg == null)
                            {
                                imgPrincipal.Visible = false;
                            }
                            else
                            {
                                if (servImg != null)
                                {
                                    DivDescr = "block";

                                    if (descrExist == 0)
                                    {
                                        imgPrincipal.Visible = true;

                                        string fotoReziseTemp = "/temp/" + servImg.Serv_img_nome;
                                        string fotoResize = "/Galeria/Servicos/" + sserv.Servicos_Id + "/" + servImg.Serv_img_nome;

                                        ResizeFoto rf = new ResizeFoto();

                                        if (lblFlag.Text.Equals("TOUR") || lblFlag.Text.Equals("SubServ"))
                                        {
                                            imgPrincipal.CssClass = "ImgPrincipalPacoteHTL";
                                            rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 292, 191);
                                        }
                                        else
                                        {
                                            imgPrincipal.CssClass = "ImgPrincipalPacoteDL";
                                            rf.RetornaImgHTL(fotoResize, fotoReziseTemp, 162, 128);
                                        }


                                        imgPrincipal.ImageUrl = UrlEmpresa + fotoReziseTemp;
                                    }

                                    //imgPrincipal.ImageUrl = UrlEmpresa + "/Galeria/Servicos/" + sserv.Servicos_Id + "/" + servImg.Serv_img_nome;
                                }
                                else
                                {
                                    DivDescr = "block";

                                    if (descrExist == 0)
                                    {
                                        imgPrincipal.Visible = true;

                                        if (lblFlag.Text.Equals("TOUR") || lblFlag.Text.Equals("SubServ"))
                                        {
                                            imgPrincipal.CssClass = "ImgPrincipalPacoteHTL";
                                        }
                                        else
                                        {
                                            imgPrincipal.CssClass = "ImgPrincipalPacoteDL";
                                        }


                                        imgPrincipal.ImageUrl = UrlEmpresa + "/images/arrival.png";
                                    }
                                }

                            }

                        }

                    }


                    switch (lblFlag.Text)
                    {
                        case "HOTEL":
                            imgIcon.Visible = true;
                            imgIcon.ImageUrl = UrlEmpresa + "/images/Icones/hotel-icon-mini.png";
                            break;
                        case "MEAL":
                            imgIcon.Visible = true;
                            imgIcon.ImageUrl = UrlEmpresa + "/images/Icones/breakfast.png";
                            break;
                        case "TRANSFER":
                            imgIcon.Visible = true;
                            imgIcon.ImageUrl = UrlEmpresa + "/images/Icones/transfer-icon-mini2.png";
                            break;
                        case "TOUR":
                            imgIcon.Visible = true;
                            imgIcon.ImageUrl = UrlEmpresa + "/images/Icones/tour-mini.png";
                            break;
                        case "EXTRA":
                            imgIcon.Visible = true;
                            imgIcon.ImageUrl = UrlEmpresa + "/images/Icones/transfer-icon-mini2.png";
                            break;
                        case "SubServ":
                            imgIcon.Visible = true;
                            imgIcon.ImageUrl = UrlEmpresa + "/images/Icones/transfer-icon-mini2.png";
                            break;
                    }

                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnAddValoresExtra_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<int, decimal> ValoresExtras = new Dictionary<int, decimal>();

                foreach (DataListItem item in dlValoresServExtra.Items)
                {
                    TextBox txtValorServExtra = (TextBox)item.FindControl("txtValorServExtra");
                    Label lblIdExtra = (Label)item.FindControl("lblIdExtra");

                    ValoresExtras.Add(Convert.ToInt32(lblIdExtra.Text), Convert.ToDecimal(txtValorServExtra.Text));
                }

                Session["ValoresExtras"] = ValoresExtras;

                if (FlagFirst.Equals("N"))
                {
                    MontaSeguintes();
                    ChangeDlQuote();
                }

                ModalPopupValueExtra.Hide();

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnOrdenar_Click(object sender, EventArgs e)
        {
            try
            {
                ModalPopupOrdem.Show();

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnAddOrdem_Click(object sender, EventArgs e)
        {
            try
            {
                TBItineraryDAL tbid = new TBItineraryDAL();

                foreach (DataListItem item in dlNomesQuote.Items)
                {
                    Label lblIdItinerary = (Label)item.FindControl("lblIdItinerary");
                    TextBox txtOrdem = (TextBox)item.FindControl("txtOrdem");

                    TBItinerary tbi = new TBItinerary();

                    tbi.Ordem = Convert.ToInt32(txtOrdem.Text);
                    tbi.Itinerary_id = Convert.ToInt32(lblIdItinerary.Text);

                    tbid.AtualizarORDEM(tbi);


                    FileTarifasDAL ftd = new FileTarifasDAL();
                    FileServExtraDAL fsed = new FileServExtraDAL();
                    FileTransfersDAL ftrand = new FileTransfersDAL();

                    TBItinerary tbiIt = tbid.ObterPorId(Convert.ToInt32(lblIdItinerary.Text));

                    switch (tbiIt.Flag)
                    {
                        case "HOTEL":

                            File_Tarifas ft = ftd.ObterPorId(Convert.ToInt32(tbiIt.idTabela));

                            File_Tarifas ftUpd = new File_Tarifas();

                            ftUpd.Ordem = Convert.ToInt32(txtOrdem.Text.Trim());
                            ftUpd.File_Tarifas_id = ft.File_Tarifas_id;

                            ftd.AtualizarOrdem(ftUpd);

                            break;

                        case "TRANSFER":

                            File_Transfers ftrs = ftrand.ObterPorId(Convert.ToInt32(tbiIt.idTabela));

                            File_Transfers ftrsUpd = new File_Transfers();

                            ftrsUpd.Ordem = Convert.ToInt32(txtOrdem.Text.Trim());
                            ftrsUpd.File_Transf_id = ftrs.File_Transf_id;

                            ftrand.AtualizarOrdem(ftrsUpd);

                            break;

                        case "SubServ":

                            File_Transfers ftrsub = ftrand.ObterPorId(Convert.ToInt32(tbiIt.idTabela));

                            File_Transfers ftrsubUpd = new File_Transfers();

                            ftrsubUpd.Ordem = Convert.ToInt32(txtOrdem.Text.Trim());
                            ftrsubUpd.File_Transf_id = ftrsub.File_Transf_id;

                            ftrand.AtualizarOrdem(ftrsubUpd);

                            break;

                        case "EXTRA":

                            File_ServExtra ftrextsub = fsed.ObterPorId(Convert.ToInt32(tbiIt.idTabela));

                            File_ServExtra ftrextsubUpd = new File_ServExtra();

                            ftrextsubUpd.Ordem = Convert.ToInt32(txtOrdem.Text.Trim());
                            ftrextsubUpd.File_ServExtra_id = ftrextsub.File_ServExtra_id;

                            fsed.AtualizarOrdem(ftrextsubUpd);

                            break;

                    }

                }


                dlQuote.DataSource = tbid.ListarTodosCode(ViewState["Code"].ToString(), 1);
                dlQuote.DataBind();

                ChangeDlQuote();

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void lnkGerarLink_Click(object sender, EventArgs e)
        {
            string url = HttpContext.Current.Request.Url.AbsoluteUri;

            Response.Redirect(url + ViewState["Code"].ToString());
        }

        protected void ExportWord(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Charset = "";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.ContentType = "application/msword.doc";
            Response.AddHeader("content-disposition", "attachment;filename=" + "Quo.doc");

            StringBuilder sbResponseString = new StringBuilder();

            String wordHeader = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"";
            wordHeader += "xmlns:w=\"urn:schemas-microsoft-com:office:word\"";
            wordHeader += "xmlns=\"http://www.w3.org/TR/REC-html40\">";
            wordHeader += "<head><title>Document Title</title>";
            wordHeader += "<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom>";
            wordHeader += "<w:DoNotOptimizeForBrowser/></w:WordDocument></xml><![endif]-->";
            wordHeader += "<style> @page Section1 {size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1;";
            wordHeader += "border:0px; padding:24.0pt 24.0pt 24.0pt 24.0pt; ";
            wordHeader += "margin:0.75in 0.50in 0.75in 0.50in ; mso-header-margin:.5in; ";
            wordHeader += "mso-footer-margin:.5in; mso-paper-source:0;} ";
            wordHeader += "div.Section1 {page:Section1;} p.MsoFooter, li.MsoFooter, ";
            wordHeader += "div.MsoFooter{margin:0in; margin-bottom:.0001pt; ";
            wordHeader += "mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; ";
            wordHeader += "font-size:12.0pt; font-family:'Arial';} ";
            wordHeader += "p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; ";
            wordHeader += "margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center ";
            wordHeader += "3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}--></style></head> ";

            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            string memoBody = "";

            LogoDiv.RenderControl(htw);
            dlQuote.RenderControl(htw);
            RatesDiv.RenderControl(htw);

            memoBody = sw.ToString();

            String wordBody = "<body><div class=Section1>" + memoBody + "</div></body></html>";

            sbResponseString.Append(wordHeader);
            sbResponseString.Append(wordBody);

            String newResponseString = sbResponseString.ToString();
            Response.Write(newResponseString);

            sw = null;
            htw = null;
            Response.Flush();
            Response.End();
        }

        //protected void btnExportPDF_Click(object sender, EventArgs e)
        //{
        //    if (FileUploadWord.HasFile)
        //    {
        //        try
        //        {
        //            if (FileUploadWord.PostedFile.ContentType == "application/msword")
        //            {
        //                if (FileUploadWord.PostedFile.ContentLength < 512000)
        //                {
        //                    string filename = Convert.ToString(Guid.NewGuid().ToString("n"));

        //                    FileUploadWord.SaveAs(Server.MapPath("~/tempWord/") + filename + ".doc");
        //                    ConvertPdf(filename);

        //                    //lblMsg.Text = "Upload status: File uploaded!";
        //                }
        //                else
        //                    lblMsg.Text = "Upload status: The file has to be less than 100 kb!";
        //            }
        //            else
        //                lblMsg.Text = "Upload status: Only Doc files are accepted!";
        //        }
        //        catch (Exception ex)
        //        {
        //            lblMsg.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        //        }
        //    }
        //    else
        //    {
        //        lblMsg.Text = "Upload status: Only Doc files are accepted!";
        //    }
        //}

        public Microsoft.Office.Interop.Word.Document wordDocument { get; set; }

        protected void ConvertPdf(string nome)
        {
            try
            {
                //Convertt(Server.MapPath("~/tempWord/") + nome + ".doc", Server.MapPath("~/tempWord/" + nome + ".pdf"), 
                //    Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);

                //Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                //wordDocument = appWord.Documents.Open(Server.MapPath("~/tempWord/") + nome + ".doc");
                //wordDocument.ExportAsFixedFormat(Server.MapPath("~/tempWord/" + nome + ".pdf"), Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);

                Microsoft.Office.Interop.Word._Application word = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(Server.MapPath("~/tempWord/") + nome + ".doc");
                doc.Activate();

                //Server.MapPath("~/tempWord/" + nome + ".pdf"
                //string path = Server.MapPath("~\\tempWord\\");

                doc.SaveAs2(Server.MapPath("~/tempWord/" + nome + ".pdf"), Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
                doc.Close();

                Response.Redirect("~/tempWord/" + nome + ".pdf", false);
            }
            catch (Exception ex)
            {
                //lblMsg.Text = ex.Message;
            }
        }

        public static void Convertt(string input, string output, Microsoft.Office.Interop.Word.WdSaveFormat format)
        {
            // Create an instance of Word.exe
            Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();

            // Make this instance of word invisible (Can still see it in the taskmgr).
            oWord.Visible = false;

            // Interop requires objects.
            object oMissing = System.Reflection.Missing.Value;
            object isVisible = true;
            object readOnly = false;
            object oInput = input;
            object oOutput = output;
            object oFormat = format;

            // Load a document into our instance of word.exe
            Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            // Make this document the active document.
            oDoc.Activate();

            // Save this document in Word 2003 format.
            oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            // Always close Word.exe.
            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        }

        protected void MostrarMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "showAutoCloseMessage('" + Msg + "')", true);
        }

        protected void rptHotel_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                Repeater rptGruposAmenities = (Repeater)e.Item.FindControl("rptGruposAmenities");

                Label lblNomeHotel = (Label)e.Item.FindControl("lblNomeHotel");
                HiddenField hdfIdHotel = (HiddenField)e.Item.FindControl("hdfIdSupplierHotel");

                if (lblNomeHotel == null)
                    return;

                Supplier s = new SupplierDAL().ObterPorId(Convert.ToInt32(hdfIdHotel.Value));

                if (rptGruposAmenities == null)
                    return;

                DataTable dt = new DataTable();
                dt.Columns.Add("supplierID");
                dt.Columns.Add("grupoAmenityID");
                dt.Columns.Add("nomeGrupoAmenity");

                List<S_SupplierAmenities> lstSupAm = new SupplierAmenityDAL().ListarPorSupplier(s.S_id);
                List<S_Amenities> lstAmenities = new List<S_Amenities>();
                if (lstSupAm == null)
                    return;
                AmenitiesDAL amDAL = new AmenitiesDAL();
                lstSupAm.ForEach(a => lstAmenities.Add(amDAL.ObterPorID((int)a.S_SupplierAmenities_Amenities_ID)));


                foreach (S_GroupAmenities group in new GroupAmenitiesDAL().ListarTodos())
                {
                    bool tem = false;

                    foreach (S_Amenities am in lstAmenities)
                        if (group.S_GroupAmenities_ID == am.S_GroupAmenities_ID)
                            tem = true;

                    if (tem)
                        dt.Rows.Add(s.S_id, group.S_GroupAmenities_ID, group.S_GroupAmenities_Name);
                }

                rptGruposAmenities.DataSource = dt;
                rptGruposAmenities.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void rptGruposAmenities_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                Repeater rptAmenities = (Repeater)e.Item.FindControl("rptAmenities");
                HiddenField hdfIDSupplier = (HiddenField)e.Item.FindControl("hdfIDSupplier");
                HiddenField hdfIDGrupoAmenity = (HiddenField)e.Item.FindControl("hdfIDGrupoAmenity");

                if ((rptAmenities == null) || (hdfIDSupplier == null) || (hdfIDGrupoAmenity == null))
                    return;

                List<S_SupplierAmenities> lstSupAm = new SupplierAmenityDAL().ListarPorSupplier(Convert.ToInt32(hdfIDSupplier.Value));
                List<S_Amenities> lstAmenities = new List<S_Amenities>();

                if (lstSupAm == null)
                    return;

                AmenitiesDAL amDAL = new AmenitiesDAL();

                lstSupAm.ForEach(a => lstAmenities.Add(amDAL.ObterPorID((int)a.S_SupplierAmenities_Amenities_ID)));

                DataTable dt = new DataTable();
                dt.Columns.Add("imgAmenity");
                dt.Columns.Add("nomeAmenity");

                foreach (S_Amenities am in lstAmenities)
                {
                    if (am.S_GroupAmenities_ID == Convert.ToInt32(hdfIDGrupoAmenity.Value))
                        dt.Rows.Add("/iconsAmenities/" + am.S_Amenities_imgNome, am.S_Amenities_nome);
                }

                rptAmenities.DataSource = dt;
                rptAmenities.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        private void CarregaTourMap()
        {
            Quotation_TourMapDAL q_md = new Quotation_TourMapDAL();

            if (Request.QueryString["Code"].Equals(""))
            {
                Quotation_TourMap qtm = q_md.ObterPorQuotationGrupoID(Convert.ToInt32(Session["SSIdQuotGrupo"]));
                if (qtm == null)
                    return;
                imgTourMap.ImageUrl = "~/Galeria/TourMaps/" + qtm.tourMap_Path;
            }
            else
            {
                TBItinerary tbi = new TBItineraryDAL().ListarTodosCode(Request.QueryString["Code"].ToString()).FirstOrDefault();
                int idQuotGrupo = new QuotationGrupoDAL().RetornaIdQuote_Grupo(tbi.Quotation_Code);
                Quotation_TourMap qtm = q_md.ObterPorQuotationGrupoID(idQuotGrupo);
                if (qtm == null)
                    return;
                imgTourMap.ImageUrl = "~/Galeria/TourMaps/" + qtm.tourMap_Path;

                //foreach (var tbi in new TBItineraryDAL().ListarTodosCode(Request.QueryString["Code"].ToString()))
                //{
                //    if ((tbi.tourmap != null) && (tbi.tourmap != ""))
                //    {
                //        imgTourMap.ImageUrl = "~/Galeria/TourMaps/" + tbi.tourmap;
                //        return;
                //    }
                //}
            }
        }

        protected void rptCities_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Repeater rptHighlights = (Repeater)e.Item.FindControl("rptHighlights");
            HiddenField hdfCityID = (HiddenField)e.Item.FindControl("hdfCityID");

            DataTable dt = new DataTable();
            dt.Columns.Add("Highlight");

            var lstft = new FileTransfersDAL().ListarTodos(Convert.ToInt32(hdfFileID.Value));

            foreach (File_Transfers ft in lstft)
            {
                if (hdfCityID.Value == ft.Trf_CID_id.ToString())
                {
                    dt.Rows.Add(ft.Transf_nome);
                }
            }
            rptHighlights.DataSource = dt;
            rptHighlights.DataBind();
        }

        protected void btnExportPDF_Click(object sender, EventArgs e)
        {
            if (FileUploadWord.HasFile)
            {
                try
                {
                    if (FileUploadWord.PostedFile.ContentType == "application/msword")
                    {
                        if (FileUploadWord.PostedFile.ContentLength < 512000)
                        {
                            string filename = Convert.ToString(Guid.NewGuid().ToString("n"));

                            FileUploadWord.SaveAs(Server.MapPath("~/tempWord/") + filename + ".doc");
                            ConvertPdf(filename);

                            //lblMsg.Text = "Upload status: File uploaded!";
                        }
                        else
                            Response.Write("Upload status: The file has to be less than 100 kb!");
                    }
                    else
                        Response.Write("Upload status: Only Doc files are accepted!");
                }
                catch (Exception ex)
                {
                    Response.Write("Upload status: The file could not be uploaded. The following error occured: " + ex.Message);
                }
            }
            else
            {
                Response.Write("Upload status: Only Doc files are accepted!");
            }
        }
    }
}